在 jQuery 中获取列表元素内容的数组

我有一个这样的结构:

<ul>
<li>text1</li>
<li>text2</li>
<li>text3</li>
</ul>

如何使用 javascript 或 jQuery 将文本作为数组?

['text1', 'text2', 'text3']

在这之后,我的计划是将它组装成一个字符串,可能使用 .join(', '),并得到一个像下面这样的格式:

'"text1", "text2", "text3"'
200413 次浏览
var optionTexts = [];
$("ul li").each(function() { optionTexts.push($(this).text()) });

...should do the trick. To get the final output you're looking for, join() plus some concatenation will do nicely:

var quotedCSV = '"' + optionTexts.join('", "') + '"';
var arr = new Array();


$('li').each(function() {
arr.push(this.innerHTML);
})

And in clean javascript:

var texts = [], lis = document.getElementsByTagName("li");
for(var i=0, im=lis.length; im>i; i++)
texts.push(lis[i].firstChild.nodeValue);


alert(texts);

Without redundant intermediate arrays:

var arr = $('li').map(function(i,el) {
return $(el).text();
}).get();

See jsfiddle demo

kimstik was close, but not quite.

Here's how to do it in a convenient one-liner:

$.map( $('li'), function (element) { return $(element).text() });

Here's the full documentation for jQuery's map function, it's quite handy: http://api.jquery.com/jQuery.map/

Just to answer fully, here's the complete functionality you were looking for:

$.map( $('li'), function (element) { return $(element).text() }).join(', ');

You may do as follows. one line of code will be enough

  • let array = $('ul>li').toArray().map(item => $(item).html());
  • Get the interested element

    1. get children

    2. get the array from toArray() method

    3. filter out the results you want

let array = $('ul>li').toArray().map(item => $(item).html());
console.log(array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>text1</li>
<li>text2</li>
<li>text3</li>
</ul>