将json数组输出分配给每个< li> [英] distributing json array output to each <li>
问题描述
我有一个JSON输出,我想显示每个<li>
中的每个项目.
JSON输出如下:
var data = [
{
"MachineID":"171914",
"Cost":"13,642.41",
"Currency":"PHP"
},
{
"MachineID":"172233",
"Cost":"1,367.73",
"Currency":"PHP"
},
{
"MachineID":"41116",
"Cost":"2,608.20",
"Currency":"PHP"
},
{
"MachineID":"178077",
"Cost":"1,517.04",
"Currency":"PHP"},
{
"MachineID":"176430",
"Cost":"20,876.72",
"Currency":"PHP"
}
]
我的代码是这样:
$.each(data, function(i, obj) {
$.each(obj, function(i, val) {
$('li').append(obj.MachineID);
});
});
现在结果显示如下:
Foo 171914171914171914172233172233172233411164111641116178077178077178077176430176430176430 Bar 171914171914171914172233172233172233411164111641116178077178077178077176430176430176430
我可能忽略了jQuery.each
调用中的某些内容,并且只需要为每个<li>
显示一个MachineID,输出应如下所示:
Foo 171914 Bar 172233 Baz 41116 Qux 178077
以此类推.
如果这些元素已存在,则最好的方法是选择li
元素,对其进行迭代,并在迭代中使用索引来抓取数据.
$('li').slice(0,data.length)
.each(function(i,el){
$(this).append(data[i].MachineID);
});
我使用了.slice()
,所以如果li
元素多于数据,它将不会尝试访问不存在的数据.
演示: http://jsfiddle.net/MYC4J/ >
如果<li>
元素尚不存在,则需要创建它们:
var ul = $('ul');
$.each(data,function(i,obj) {
$('<li>',{text:obj.MachineID}).appendTo(ul);
});
演示: http://jsfiddle.net/MYC4J/1/
I have a JSON output and i want to show each item inside each <li>
.
The JSON output looks like this:
var data = [
{
"MachineID":"171914",
"Cost":"13,642.41",
"Currency":"PHP"
},
{
"MachineID":"172233",
"Cost":"1,367.73",
"Currency":"PHP"
},
{
"MachineID":"41116",
"Cost":"2,608.20",
"Currency":"PHP"
},
{
"MachineID":"178077",
"Cost":"1,517.04",
"Currency":"PHP"},
{
"MachineID":"176430",
"Cost":"20,876.72",
"Currency":"PHP"
}
]
And my code is this:
$.each(data, function(i, obj) {
$.each(obj, function(i, val) {
$('li').append(obj.MachineID);
});
});
Now the result shows like this:
Foo 171914171914171914172233172233172233411164111641116178077178077178077176430176430176430 Bar 171914171914171914172233172233172233411164111641116178077178077178077176430176430176430
I may have overlooked something on jQuery.each
call and I need only to show one MachineID per <li>
, the output should be like this:
Foo 171914 Bar 172233 Baz 41116 Qux 178077
and so on..
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/
这篇关于将json数组输出分配给每个< li>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!