如何放置所有元素'使用jQuery数组中的内容? [英] How to put all elements' content in array using jQuery ?
本文介绍了如何放置所有元素'使用jQuery数组中的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<div id="main">
<p>Text1</p>
<p>Text2</p>
<p>Text3</p>
</di>
结果应为:
["text1","text2","text3"]
推荐答案
jQuery提供了 .map()
为此:
jQuery provides .map()
for this:
var items = $('#main p').map(function () { return $(this).text(); }).get();
.map()
遍历其元素,在每个元素上调用一个函数,并将该函数的返回值记录在返回的新数组中.
.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.
您还可以通过简单的 .each()
解决此问题:
You could also have solved this with a simple .each()
:
var items = [];
$('#main p').each(function (i, e) {
items.push($(e).text());
});
这篇关于如何放置所有元素&#39;使用jQuery数组中的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文