jquery 函数内的 for 循环

发布于 2024-09-28 05:21:49 字数 247 浏览 2 评论 0原文

我试图在 jquery 函数中重复一些内容。我尝试了 for 循环,但它似乎不喜欢语法。 例如,我

var number = 2;

现在有一个变量,我

$('tr').html('<td id="'+number+'"></td>');

想要做的就是从 0 循环到数字 (0,1,2) ,这样最终我就会得到 3 。 谢谢

I am trying to repeat something inside a jquery function. I tried a for loop, but it seems it doesnt like the syntax.
for instance i have the variable

var number = 2;

now i have

$('tr').html('<td id="'+number+'"></td>');

what i want to do is loop from 0 to number (0,1,2) so that in the end i end up having 3 .
Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

很快妥协 2024-10-05 05:21:49

可能有更好的方法,但这应该可行。

var loops = [1,2,3];

$.each(loops, function(index, val) {
  $('tr').html('<td id="myCell' + index + '"></td>');
});

这也应该有效(常规 JS):

var i;
for(i=0; i<3; i++) {
  $('tr').html('<td id="myCell' + i + '"></td>');
}

请注意我如何在 id 前面添加单词“myCell”作为前缀,以确保 XHTML 合规性。 (感谢@Peter Ajtai 指出了这一点)。

编辑

我刚刚注意到另一个问题 - 您正在使用.html函数来添加单元格。但是 .html 会替换匹配元素的整个 html。所以你最终只会得到最后一个单元格。 :)

您可能正在寻找 .append 函数:

$('tr').append('<td id="myCell' + i + '"></td>');

编辑 2 - 将双引号移到 myCell 之前而不是之后。

There is probably a better way, but this should work.

var loops = [1,2,3];

$.each(loops, function(index, val) {
  $('tr').html('<td id="myCell' + index + '"></td>');
});

This should also work (regular JS):

var i;
for(i=0; i<3; i++) {
  $('tr').html('<td id="myCell' + i + '"></td>');
}

Note how i prefixed id with the word 'myCell', to ensure XHTML compliancy. (thanks to @Peter Ajtai for pointing that out).

EDIT

I just noticed another problem - you're using the .html function to add the cells. But .html replaces the entire html of the matched element. So you'll only ever end up with the last cell. :)

You're probably looking for the .append function:

$('tr').append('<td id="myCell' + i + '"></td>');

EDIT 2 -- moved the double quote before myCell rather than after.

梨涡少年 2024-10-05 05:21:49

这是使用匿名函数的选项。

$('TR').html(
    function(){
        var content=''; 
        for (var i=0; i<=2; i++  ){
            content=content+'<td id="id_'+i+'"></td>';
        }
        return content;
    }
)

Heres an option using an anonymous function.

$('TR').html(
    function(){
        var content=''; 
        for (var i=0; i<=2; i++  ){
            content=content+'<td id="id_'+i+'"></td>';
        }
        return content;
    }
)
帥小哥 2024-10-05 05:21:49

这对我有用:

 loop.forEach((amount) => { 
     // your code
}

This works for me:

 loop.forEach((amount) => { 
     // your code
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文