2012-06-12 87 views
0

的性质的嵌套阵列如果我有HTML如此:创建包含多个HTML元素

<ul> 
    <li id="id1">Some Text</li> 
    <li id="id2">Other Text</li> 
    <-- more items could be here --> 
</ul> 

如何创建一个含有JSON对象与每个列表项的列表中的属性的阵列,是这样的:

var itemsData = [ 
    { 
     "id" : id, 
     "name" : name 
    }, 
    { 
     "id" : id, 
     "name" : name 
    } 
] 

idname等于$(this).attr('id')$(this).text()其中$(this)指单个li项目。

回答

4

通过使用.each

var itemsData = []; 

$('li').each(function() { 
    var $this = $(this); 
    itemsData.push({ 
     id: $this.attr('id'), 
     name: $this.text() 
    }); 
}); 

console.log(itemsData); 
+0

是啊,我解决它以同样的方式在等待答案。它很容易,我想我只是累了。仍然有问题将你的答案标记为正确。 :) – Maverick

+0

@Husar我看到了,你有点不耐烦了吧? ;-) –

5
itemsData = []; 
$('ul > li').each(function(){ 
    itemsData.push({"id" : this.id, "name" : $(this).text()}) 
}); 

DEMO(见控制台输出)

1
var arr = new Array(); 
$("ul li").each(function(index){ 
    arr[index]['id'] = $(this).attr('id'); 
    arr[index]['name'] = $(this).attr('name'); 
});