Jquery,获取一个 text() 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16570564/
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
Jquery, get an array of text()
提问by Carlos
I am trying to get and array of text after using the text function, having a ul list like
在使用 text 函数后,我试图获取和文本数组,有一个 ul 列表,如
<ul>
<li>one
<ul>
<li>one one</li>
<li>one two</li>
</ul>
</li>
</ul>
then get something like
然后得到类似的东西
['one', 'one one', 'one two']
回答by Mohammad Adil
var array = $('li').map(function(){
return $.trim($(this).text());
}).get();
Demo Fiddle -->
http://jsfiddle.net/EC4yq/
演示小提琴-->
http://jsfiddle.net/EC4yq/
回答by Evan
You just want to get the text from all the li's?
您只想从所有 li 中获取文本?
var resultArray = [];
$('li').each(function(){
resultArray.push($(this).text());
});
回答by Nakilon
Try this:
尝试这个:
$("li").map(function(){ return this.innerText })
or this:
或这个:
$("li").toArray().map(function(i){ return i.innerText })
回答by Kevin
You could do something like
你可以做类似的事情
var children = $(listholder).children();
var array = [];
var i = 0;
$.each(children, function(key, value){
array.push($(this).text());
});
回答by rtcherry
Several of the answers ignore the OP's desired format.
一些答案忽略了 OP 所需的格式。
This will give you what you want.
这会给你你想要的。
$('li').map(function(){
var $clone = $(this).clone();
$clone.children('*').remove();
return $.trim($clone.text());
}).get()
Fiddle: http://jsfiddle.net/pE9PR/