javascript 如何使用 jQuery 将所有元素的内容放入数组中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4948770/
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 put all elements' content in array using jQuery ?
提问by faressoft
<div id="main">
<p>Text1</p>
<p>Text2</p>
<p>Text3</p>
</di>
Result should be :
结果应该是:
["text1","text2","text3"]
回答by meagar
jQuery provides .map()for this:
jQuery.map()为此提供了:
var items = $('#main p').map(function () { return $(this).text(); }).get();
.map()iterates over its elements, invoking a function on each of them and recording the return value of the function in a new array, which it returns.
.map()迭代它的元素,对每个元素调用一个函数,并将函数的返回值记录在一个新数组中,它返回。
You could also have solved this with a simple .each():
你也可以用一个简单的方法解决这个问题.each():
var items = [];
$('#main p').each(function (i, e) {
items.push($(e).text());
});
回答by AndrewC73
This will work:
这将起作用:
var p = $('#main p').map(function () {
return '"' + $(this).text() + '"';
}).get().join(',');
p = "[" + p + "]";
map() lets you iterate over each match and get a value from it, which is inserted into an array-like object. get() then returns it as a Javascript array, and .join makes the array into a string.
map() 允许您遍历每个匹配项并从中获取一个值,该值被插入到一个类似数组的对象中。get() 然后将其作为 Javascript 数组返回,而 .join 将数组变成字符串。

