2013-03-03 159 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() 
       }); 
});