javascript 如何使用 jQuery 在数组中存储列表项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31330892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store list items within an array with jQuery
提问by Pablo Darde
I want to store all list items of several list of the same class within an array.
我想将同一类的多个列表的所有列表项存储在一个数组中。
for exemple:
举个例子:
<ul class="myList">
<li>item 1</li>
<li>item 2</li>
</ul>
<ul class="myList">
<li>item 3</li>
<li>item 4</li>
<li>item 5</li>
</ul>
Script file:
脚本文件:
var arr_list_items = [];
$('ul.myList').each(function(){
while( !$(this).empty() ) {
list_item = $(this).find('li:first');
arr_list_items.push( list_item );
list_item.remove();
}
});
The list items are removed, but the array returns empty.
列表项被删除,但数组返回空。
Thanks
谢谢
回答by 74U n3U7r1no
var array = [];
$('.myList li').each(function(i, li) {
array.push($(li));
});
回答by Josh Crozier
No need for any complex logic.
不需要任何复杂的逻辑。
You can use the .get()
methodto retrieve an array of the elements matched by the jQuery object:
您可以使用该.get()
方法检索与 jQuery 对象匹配的元素数组:
var arr_list_items = $('.myList li').remove().get();
console.log(arr_list_items);
// [li, li, li, li, li]
Alternatively, you could also use the .map()
method:
或者,您也可以使用以下.map()
方法:
var arr_list_items = $('.myList li').remove().map(function () {
return this;
}).get();
回答by Sky Fang
var arr_list_items = [];
$('ul.myList').each(function (i,n) {
$(n).find('li').each(function (j, m) {
arr_list_items.push(m);
}).remove();
});
for (var i = 0; i < arr_list_items.length; i++) {
console.info(arr_list_items[i]);
}
Because I am poor in English, so I can not explain the code,but I think you can understand it
因为我英文很差,所以我无法解释代码,但我想你能看懂
回答by sbonkosky
var arr_list_items = [];
$('ul.myList').each(function(){
$(this).find('li').each(function(){
arr_list_items.push(this);
$(this).remove();
});
});
console.info(arr_list_items);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="myList">
<li>item 1</li>
<li>item 2</li>
</ul>
<ul class="myList">
<li>item 3</li>
<li>item 4</li>
<li>item 5</li>
</ul>