jquery - 将数字添加到表中

标签 jquery loops

我尝试使用 .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 等等。

最佳答案

试试这个

$(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 #
    });
});

Fiddle

关于jquery - 将数字添加到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16908295/

相关文章:

javascript - 延迟对象如何通知它已解决的 promise ?

java - 错误 com JSONP e Jersey 2.4.1

jQuery 处理表单

Javascript 在 foreach 之外添加一个元素,但它们是连接而不是添加

python - 为什么lambda函数保持循环最后一步的形式?

java - 遍历对象的变量(java)

javascript - 从 javascript 加载和缓存脚本

javascript - jquery 将日期转换为格式化日期

linux - 如何在Linux shell中循环相同格式的文件

javascript - 如何减少 Javascript 中的两个循环以提高效率