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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:06:43  来源:igfitidea点击:

jquery collect value of list items and place in array

javascriptjquery

提问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.

  • map()(文档)方法创建填充无论是从函数返回一个jQuery对象(在这种情况下,每个的文本内容<li>元素)。

  • get()(文档)的方法(当传递无参数)该jQuery对象转换成实际的数组。

回答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(); });