jQuery 使用选择器而不是迭代获取文本值数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3496318/
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
Get array of text values using selector instead of iterating?
提问by user246114
I have some HTML like:
我有一些 HTML,如:
<ul id='foo'>
<span><a>hello 1</a></span>
<span><a>hello 2</a></span>
<span><a>hello 3</a></span>
</ul>
I want to get an array of all the text values of the elements like:
我想获取元素的所有文本值的数组,例如:
var texts = [ 'hello 1', 'hello 2', 'hello 3' ];
I'm trying to iterate over each one, is there some way in jQuery to just grab all of them using a selector?
我正在尝试遍历每一个,在 jQuery 中是否有某种方法可以使用选择器来获取所有这些?
回答by Nick Craver
回答by George Herolyants
Or a little bit shorter than the accepted answer:
或者比接受的答案短一点:
$.map($("#foo span a"), $.text)
回答by jmar777
Try this:
尝试这个:
$('#foo span a').map(function() { return $(this).text(); }).get();
回答by ovais.tariq
you can do it like this
你可以这样做
var texts = new Array();
$('#foo > span > a').each(function()
{
texts.push( $( this ).text() );
});
回答by JerryGoyal
Additionally, the function to get the array of values with trimmed spaces:
此外,获取带有修剪空格的值数组的函数:
var array = $('li').map(function(){
return $.trim($(this).text());
}).get();
回答by treeface
Try this:
尝试这个:
var texts = new Array();
//or... var texts = [];
$('#foo a').each(function() {
texts.push($(this).text());
})
回答by codersarepeople
use the jquery selector:
使用 jquery 选择器:
$("ul#foo span a")