jquery 遍历 table 列中所有单元格的循环脚本

jquery loop script through all cells in a column of a table

仅供参考,我在 jquery 方面很糟糕,非常非常糟糕。

好吧,问题来了,我有一个 table,我想格式化第 5 列中每个单元格的数字到目前为止,我的脚本只适用于第 5 列中的第一个单元格,然后它在其余单元格上复制第一个单元格,而我希望它遍历每个单元格并提供唯一的单元格值。

我在用我的脚本做什么

  1. 我正在为第 5 列的每个单元格添加一个 ID(我无法手动添加一个,因此这是我唯一可以做到的方法)
  2. 我要添加一个 £,然后将数字格式化为小数点后两位
  3. 最后,我需要对所有 id 'test'
  4. 实例重新运行第 2 步

我正在处理这样的数字

如您所见,这读起来很糟糕,这就是我编写此脚本的原因。

我已经在底部添加了我的代码。

感谢所有帮助。

$(document).ready(function(){
    $('table>tbody>tr>td:nth-child(5n)').prop('id', 'test');
    $('#test').each(function(){
        var test = parseFloat($('#test').text()).toFixed(2);
        $('table>tbody>tr>td:nth-child(5n)').empty().append('£', test);
    });
});

根据 JQuery 文档,id selector 将 select 为单个元素。 使用 class 可以轻松地选择多个元素。您可以像这样添加 class:

$('table>tbody>tr>td:nth-child(5n)').addClass('formatted');

然后 select 个元素由 class:

$('.formatted').each(function(){
    var test = parseFloat($(this).text()).toFixed(2);
    $('table>tbody>tr>td:nth-child(5n)').empty().append('£', test);
});

另请注意 select 或 each 函数内部已从 $('#test') 更改为 $(this)。在第一种情况下,您总是 select 带有 id=test 的第一个元素,而在后一种情况下,您将获得循环中的当前元素。