最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - for loop inside jquery function - Stack Overflow

programmeradmin5浏览0评论

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

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

Share Improve this question edited Oct 19, 2010 at 3:59 Goyuix 24.4k15 gold badges89 silver badges130 bronze badges asked Oct 19, 2010 at 3:44 El FuserEl Fuser 4412 gold badges6 silver badges10 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

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 pliancy. (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.

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

This works for me:

 loop.forEach((amount) => { 
     // your code
}
发布评论

评论列表(0)

  1. 暂无评论