javascript jquery 收集列表项的值并放入数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4856283/
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
jquery collect value of list items and place in array
提问by sea_1987
If I have the following HTML:
如果我有以下 HTML:
<ul>
  <li>List 1</li>
  <li>list 2</li>
  <li>list 3</li>
</ul>
Can I get the text content from the the <li>'s and place them in array using javascript?
我可以从<li>'s获取文本内容并使用 javascript 将它们放在数组中吗?
回答by Luke
var arr = $("li").map(function() { return $(this).text() }).get();
- The - map()(docs)method creates a jQuery object populated with whatever is returned from the function (in this case, the text content of each- <li>element).
- The - get()(docs)method (when passed no argument) converts that jQuery object into an actual Array.
回答by KARASZI István
var x = [];
$("ul li").each(function() {
  x.push($(this).text());
});
or simply:
或者干脆:
var x = $.map($("ul li"), function( i ) { return $(i).text(); });

