0

我使用 jQuery 的 .each() 函数遇到了这个问题。我想对我拥有的表的行和列进行排序,我试图通过将名为“row”和“col”的属性添加到我的“td”标签来实现。

基本上我的代码如下所示:

$('tr').each(function(tr_index) {
    $('td').each(function(td_index) {
        $(this).attr({
            'row' : tr_index,
            'col' : td_index,
        });
    });
});

但这给了我以下输出:

<td row="6" col="0"></td>
<td row="6" col="1"></td>
<td row="6" col="2"></td>
<td row="6" col="3"></td>
<td row="6" col="4"></td>
<td row="6" col="5"></td>
<td row="6" col="6"></td>

row 属性在每个“td”标签上输出 6。这是否意味着第一个 .each() 循环在任何第二个 .each() 循环被触发之前执行?

任何想法我可以如何改变它,以便我有这样的东西:

<td row="0" col="0"></td>
<td row="0" col="1"></td>
<td row="0" col="2"></td>
<td row="1" col="0"></td>
<td row="1" col="1"></td>
<td row="1" col="2"></td>
<td row="2" col="0"></td>

ETC...

如果有人能为我解决这个问题,我将不胜感激,因为我似乎无法解决这个问题。

4

1 回答 1

5

试试这个

        $('tr').each(function(idx_row){
            $(this).children().each(function(idx_col){
                $(this).attr({'row':idx_row, 'col':idx_col});
            })
        });
于 2012-07-10T00:37:24.427 回答