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

javascript - For loop only running once in Jquery - Stack Overflow

programmeradmin2浏览0评论

Having an issue with a for loop in jQuery only running once. Users is a array containing 4 items, and for each, it should append that item as a list element to userList, which is a ul. It appends the first element in the array as expected, but only that one. Not sure why it isn't running through the entire array?

$(document).ready(function() {
    var $currentUser = $('<li class="user"></li>');
    for(var i = 0; i < users.length; i++) {
        $currentUser.text(users[i]);
        $currentUser.appendTo('.userList');
    }    
    //alert(users.length) returns "4".
});

Having an issue with a for loop in jQuery only running once. Users is a array containing 4 items, and for each, it should append that item as a list element to userList, which is a ul. It appends the first element in the array as expected, but only that one. Not sure why it isn't running through the entire array?

$(document).ready(function() {
    var $currentUser = $('<li class="user"></li>');
    for(var i = 0; i < users.length; i++) {
        $currentUser.text(users[i]);
        $currentUser.appendTo('.userList');
    }    
    //alert(users.length) returns "4".
});
Share Improve this question edited Apr 8, 2015 at 1:25 Terry 14.2k9 gold badges57 silver badges84 bronze badges asked Apr 8, 2015 at 1:12 user4313867user4313867 1
  • 4 You don't create one <li> per user, you create one and overwrite its contents every iteration. – zerkms Commented Apr 8, 2015 at 1:17
Add a ment  | 

5 Answers 5

Reset to default 5

Try this

$(document).ready(function(){
for(var i = 0; i < users.length; i++) {
    var $currentUser = $('<li class="user"></li>');
    $currentUser.text(users[i]);
    $currentUser.appendTo('.userList');
  }
});

You're overwriting the element, instead of creating a new one for each user. Try the code above.

More jQuery'ish

$('.userList').append(function() {
    return $.map(users, function(user) { 
        return $('<li />', {
            'class' : 'user',
            text    : user
        })
    });
});

FIDDLE

You aren't adding a new <li> for each iteration:

Here's a working solution:

for (var i = 0; i < users.length; i++) {
    $('<li class="user"></li>'
        .text(users[i])
        .appendTo('.userList');
}

https://jsfiddle/2abqa5us/1/

You create the li on the outside of the loop, then try to set the text of the same element to each user so you will overwrite it every iteration. Are you sure the last entry is not the one you see?

.text will overwrite previous text which looks like you got one users only

try this.

$(document).ready(function(){

    for(var i = 0; i < users.length; i++) {
        var $currentUser = $('<li class="user"></li>');
        $currentUser.text(users[i]);
        $currentUser.appendTo('.userList');
    }


});
发布评论

评论列表(0)

  1. 暂无评论