开发者

jQuery each does not execute html for each element in object

Here's the code:

var object = [
  {'item1': 'value1a', 'item2':'value2a', 'item3':'value3a'},
  {'item1': 'value1b', 'item2':'value2b', 'item3':'value3b'},
];


$.each(object, function(key,value) { 
  $('.my-div').html('<li>'+ value.item1 + '</li>');
});

This outputs only one <li>value1b</li>. For some reason skips 开发者_JS百科over all except the last iteration.

Thoughts?


It's overwriting all your HTML instead of appending it.

Change

$('.my-div').html('<li>'+ value.item1 + '</li>');

to

$('.my-div').append('<li>'+ value.item1 + '</li>');

Working demo: http://jsfiddle.net/AlienWebguy/hpLa6/1/


The previous edits are being overwritten. Its the equivalent of doing this:

int total = 0;
for (int x=0;x<10;++x)
   total = x;

(obviously a different programming language)

The above answer would be "9" instead of the expected answer.

You need to append each html call.

Edit:

Holy crap people beat me... :-(


You are overwriting it on each iteration. You need to do like

$('.my-div').html($('.my-div').html()+'<li>'+ value.item1 + '</li>');

edited to fix bug


Is it necessary to use jQuery for this, why not just use a simple:

for (var obj in objects) {
    $('.my-div').append('<li>'+ obj.item1 + '</li>');
}

Tip: I would avoid using the id object in any language


Since some people like to downvote because of inefficiency... this would be more efficient, as it selects the node only once

$(function(){
      var object = [
          {'item1': 'value1a', 'item2':'value2a', 'item3':'value3a'},
          {'item1': 'value1b', 'item2':'value2b', 'item3':'value3b'},
      ];

    var content = '';
    $.each(object, function(key,value) { 
       content += '<li>'+ value.item1 + '</li>';    
    });
    $('.my-div').html(content);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜