distributing json array output to each <li>

 ̄綄美尐妖づ 提交于 2019-12-05 22:15:48

If these are existing li elements, the best way would be to select the li elements, iterate them, and use the index in the iteration to grab the data.

$('li').slice(0,data.length)
       .each(function(i,el){
           $(this).append(data[i].MachineID);
       });

I used .slice() so that if there are more li elements than data, it won't try to access non-existent data.

Demo: http://jsfiddle.net/MYC4J/


If the <li> elements do not yet exist, then you'd need to create them:

var ul = $('ul');

$.each(data,function(i,obj) {
    $('<li>',{text:obj.MachineID}).appendTo(ul);
});

Demo: http://jsfiddle.net/MYC4J/1/

Because you go through each object and each property you append for every object 3 times the MashineId.

You only need 1 $.each-loop and append the MashineId to the right li.

Something like that:

$.each(data, function(index, value){
   $("ul li:nth-child(" + (index+1) + ")").append(value.MashineId);
});

nth-child() selects the li (1-based index) and appends the MashineId. That is for the case that your MashineIds are simply added to the next li. Perhaps you need for your case another logic to find the right li.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!