javascript jquery函数中的for循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3965192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:51:02  来源:igfitidea点击:

for loop inside jquery function

javascriptjqueryloops

提问by El Fuser

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

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

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

我想要做的是从 0 循环到数字 (0,1,2) 以便最后我得到 3 。谢谢

回答by RPM1984

There is probablya 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):

这也应该有效(常规 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).

请注意我是如何在 id 前面加上“myCell”这个词的,以确保符合 XHTML。(感谢@Peter Ajtai 指出这一点)。

EDIT

编辑

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

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

You're probably looking for the .appendfunction:

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

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

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

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

回答by Michael MacDonald

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;
    }
)