Fw: [問題] jQuery .each index問題
※ [本文轉錄自 java 看板 #1SZXGzwb ]
作者: kiloxx (名器) 看板: java
標題: [問題] jQuery .each index問題
時間: Sun Mar 17 17:32:43 2019
大家好~~
(我是超級新手,程式基礎只有python,最近在學習建造dashboard)
想問一個jQuery each的問題: index開始的位子從0變成1了
下圖是我的function,是讓table插入一個新column
source是原本table的data
function add_columns(id, source) {
var $table = $(`#${id}`)
$table.find('tr').each(function (index) {
console.log(source[index], index, source.length);
if ( source[index] != undefined ) {
$(this).find('td').eq(-1).after(`
<td id="${source[index][0]}">
</td>
`
);
}
}
我在console loop出來,假設source = [ [0], [1], [2] ]
[0] , 0, 3
[1] , 1, 3
[2] , 2, 3
undefined, 3, 3
但是我產生出來的對應的td卻只有
<td id=1></td>
<td id=1></td>
<td id=2></td>
<td id=2></td>
null
null
這邊很明顯就是在進到if的時候,index變成1開始了,不是0
請問為什麼會這樣? 是我coding哪裡有問題嗎?還是這是正常的?
我暫時先在if 裡面用index-1來處理掉,但感覺又怪怪的
抱歉打得有點長,麻煩幫忙解惑!!
感恩
// edited 已解決
睡不著突然想通了,$(tr)包含thead,
但是thead 沒有td,所以if statement 裡面才會從1開始
也可以解釋為何多loop一次了
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.243.154.240
※ 文章網址: https://www.ptt.cc/bbs/java/M.1552815165.A.EA5.html
※ 文章網址: https://www.ptt.cc/bbs/java/M.1552815165.A.EA5.html
→
03/17 18:30,
6年前
, 1F
03/17 18:30, 1F
推
03/17 18:59,
6年前
, 2F
03/17 18:59, 2F
→
03/17 19:09,
6年前
, 3F
03/17 19:09, 3F
※ 發信站: 批踢踢實業坊(ptt.cc)
※ 轉錄者: kiloxx (111.243.154.240), 03/17/2019 19:09:35
→
03/18 00:27,
6年前
, 4F
03/18 00:27, 4F
→
03/18 00:27,
6年前
, 5F
03/18 00:27, 5F
→
03/18 01:35,
6年前
, 6F
03/18 01:35, 6F
→
03/18 01:35,
6年前
, 7F
03/18 01:35, 7F
→
03/18 01:37,
6年前
, 8F
03/18 01:37, 8F
→
03/18 13:18,
6年前
, 9F
03/18 13:18, 9F
→
03/18 13:20,
6年前
, 10F
03/18 13:20, 10F
→
03/18 13:20,
6年前
, 11F
03/18 13:20, 11F
→
03/18 23:47,
6年前
, 12F
03/18 23:47, 12F
→
03/18 23:48,
6年前
, 13F
03/18 23:48, 13F
→
03/19 00:27,
6年前
, 14F
03/19 00:27, 14F
→
03/19 00:28,
6年前
, 15F
03/19 00:28, 15F
→
03/19 00:28,
6年前
, 16F
03/19 00:28, 16F
→
03/19 01:56,
6年前
, 17F
03/19 01:56, 17F
推
03/20 00:26,
6年前
, 18F
03/20 00:26, 18F
還是不知道為什麼...我console看也都是對的...
所以我換了一個寫法先loop source比較好
function add_columns(id, source) {
let $table = $(id);
$.each(source, function (index, value) {
let tr = $table.find('tr');
let td = document.createElement('td');
td.innerHTML = value;
//+1 to skip <thead>
tr[index+1].append(td);
tr[index+1].append(td);
});
};
不好意思打擾大家
※ 編輯: kiloxx (111.248.80.42), 03/20/2019 01:22:01
※ 編輯: kiloxx (111.248.80.42), 03/20/2019 02:11:24
※ 編輯: kiloxx (111.248.80.42), 03/20/2019 02:12:09
Web_Design 近期熱門文章
PTT數位生活區 即時熱門文章