【问题标题】:Repeat a javascript code with a different number in each run在每次运行中重复使用不同数字的 javascript 代码
【发布时间】:2016-05-12 05:52:16
【问题描述】:

我不知道术语,但希望这个解释是有道理的。我有一个 JavaScript 代码,我想重复 10 次,每次都增加数量以针对表中的每个 td(第一个 td 然后是第二个然后是第三个,依此类推)

此 JavaScript 的目标是将 thead 的 TD 宽度与 tbody 中的宽度相匹配(这是因为我通过 css 将它们分开,位置:absolute)。

现在我设法用这个来匹配单个 TD 的宽度:

var cell4 = $('#divResults tbody > td:nth-child(4)');
$('#divResults thead > tr > td:nth-child(4)').css({ width: cell4.width()});

完成设置剩余 TD 的最简单但不实用的方法是复制 JS,但将数字替换 9 次以上。

我知道有一种方法可以创建循环并针对每个 TD,而无需手动复制代码,但似乎无法在线找到答案。

感谢您的帮助

【问题讨论】:

  • 您要查找的是for loop
  • 我感谢所有 cmets 并尝试应用每个 cmets 以查看最有效的方法应该进一步澄清,tbody 中的每个 td 具有不同的宽度,所以我想将每个 td 与它们各自的宽度相匹配宽度。因此,我需要使 thead td1 与 tbody td1 匹配,使 tbody td2 与 thead td2 匹配,依此类推...

标签: javascript jquery html html-table


【解决方案1】:

不要选择特定元素,而是选择所有元素并循环遍历它们。

$('#divResults tbody > td').each(function( index ) {
  // Do some repeating code
});

链接了解更多详情 https://api.jquery.com/each/

【讨论】:

    【解决方案2】:

    在 vanilla JS 中,您将使用 for 循环来实现这一点。使用 jQuery,您可以获取 <td>s 的集合并使用 .each 循环遍历它们

    // Get the first tr's collection of td elements
    var bodyTds = $('#divResults tbody tr:first-child td');
    
    // Loop over the head td's (should be th's really)
    $('#divResults thead tr td').each(function(index) {
        // Apply the width of the body td to the head td
        $(this).css({ width: bodyTds.eq(index).width()});
    });
    

    【讨论】:

    • 我相信 OP 希望 head.eq(index).css(...) " 将 thead 的 TD 宽度与 tbody 中的宽度相匹配"
    • 哎呀,你说得对……这就是为什么我把第一个孩子放进去,但没有切换 tbody 和 thead。感谢现场。
    猜你喜欢
    • 2013-11-29
    • 2017-10-20
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    相关资源
    最近更新 更多