2013-03-03 57 views
0

其裏的值保存到數組,我想OL迭代,並保存所有理成陣列如何遍歷DOM OL和使用jquery

<ol id="sortableAvailable"> 
    <li id="1"><a href="" >Foo 1</a></li> 
    <li id="2"><a href="" >Foo 2</a></li> 
    <li id="3"><a href="" >Foo 3</a></li> 
    <li id="4"><a href="" >Foo 4</a></li> 
</ol> 

JS應該是財產以後這樣的:

var testInfoList = {}; 
testInfoList.ConfiguredTests = [];  


/* some iteration that do the following */ 
testInfoList.ConfiguredTests.push({ 
    ID: /*here i want the ID*/, 
    Value: /*here i want the value*/ 
}); 
+1

$(「#sortableAvailable li」)。each(function(){...}); – mplungjan 2013-03-03 06:46:06

回答

2

您可以使用.map

testInfoList.ConfiguredTests = = $("#sortableAvailable li").map(function() { 
    return { ID:this.id, Value:$(this).find("a").text() }; 
}).get(); 

map將遍歷您的元素(選定查找所有列表中的li)並將函數應用於它們中的每一個。結果將是一個jQuery對象,可以使用.get()將其提取回數組。

我假設的「價值」是指鏈接內的文字;如果你想要別的東西,你可以從當前元素中提取它(this是DOM元素,$(this)將它包裝在一個jQuery對象中)。

1
var myarray = [];  

$("ol li").each(function(){ 
    myarray.push({ 
        ID: $(this).attr('id'), 
        Value: $(this).html() 
       }); 
});