我想在循环中将所有text
的值存储到数组中,这是可能的吗?有人可以给我一些提示如何做到这一点吗?
$('#wa li').each(function (i) {
var text = $(this).text();
});
我想在循环中将所有text
的值存储到数组中,这是可能的吗?有人可以给我一些提示如何做到这一点吗?
$('#wa li').each(function (i) {
var text = $(this).text();
});
const liTexts =
$ ('#wa li')
.map ((idx,elem) => $(elem).text ())
.get ()
console.log (liTexts)
// [ 'one', 'two', 'three' ]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="wa">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
var myArr = []; // define the array
$('#wa li').each(function (i) {
myArr.push($(this).text()); // push the value into the array
});
console.log(myArr); // ['hello', 'world', ...] use the array
array.push()
将值添加到数组中。var myArr = []; // define the array
$('#wa li').each(function (i) {
myArr.push($(this).text());
});
.map()
是解决这个问题的好方法。) - nnnnnnthis
来引用元素,所以如果您也想要索引,您只需在回调中定义一个参数即可。 - nnnnnnthis
,20% 闭包,20% 打错字,20% 没有阅读易于获取的文档,20% 帮我编写代码。 (好吧,我不应该说是100%,还有好的、非重复的问题。) - nnnnnn