2012-06-12 85 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'); 
});