1

我试图通过javascript使用.length循环遍历整个表并列出每行的数字,通过javascript向每个表行添加一个数字。我一直在努力工作,但我一直失败。请帮忙!这是我的桌子:

<table class="mytable">
    <thead>
        <tr>
            <th>#</th>
            <th>First</th>
            <th>Last</th>
        </tr>
    </thead>
    <tbody>
        <tr class="person">
            <td class="number"></td>
            <td>Bill</td>
            <td>Sims</td>
        </tr>
        <tr class="person">
            <td class="number"></td>
            <td>Jenny</td>
            <td>Jackson</td>
        </tr>
        <tr class="person">
            <td class="number"></td>
            <td>Milo</td>
            <td>Resa</td>
        </tr>
    </tbody>
</table>`

所以理想情况下它看起来像这个 1 Bill Sims 等等。

4

3 回答 3

3

尝试这个

$(function(){
    $('.mytable tr').each(function(i){
        $(this).find('td:first').text(i); // or $(this).find('td.number').text(i);
  //Use iterator's index argument 
    });
});

或者

$(function(){
    $('.mytable tr td.number').text(function(){
       return $(this).closest('tr').index() + 1; // get the parent tr's index() add 1 to get the #
    });
});

小提琴

于 2013-06-04T01:13:44.823 回答
2

我敢打赌你从其他帖子中得到了答案,但我更喜欢在通过孩子选择父母时使用父母直接父母而不是递归旅行),而不是在选择父母的直接孩子时使用最接近孩子和孩子(不遍历孩子的后代),因为 td 始终是 tr 的直接孩子。

例子:

$('table tr td.number').each(function(){
    $(this).text($(this).parent().index()+1); // you could use collection (like the next example) if you have one td with class 'number' per each tr
});

或者:

$('table tr').each(function(i){
    $(this).children('.number:first').text(i+1);
});

问候,

于 2013-06-04T01:38:12.690 回答
1

尝试这个

$('table tr').each(function() {
   var index = $(this).index();
    $('.number', this).text(index +1);
});

检查小提琴

于 2013-06-04T01:15:18.420 回答