jQuery jQuery选择属性到数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7055053/
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 select attributes into an array
提问by David Weng
What's the most elegant way to get this array
获取此数组的最优雅方法是什么
[10, 20, 30, 40, 50]
out of this list
不在这个名单上
<ul>
<li value="10">Item One</li>
<li value="20">Item Two</li>
<li value="30">Item three</li>
<li value="40">Item Four</li>
<li value="50">Item Five</li>
</ul>
using jQuery.
使用 jQuery。
回答by samccone
****edit****
****编辑****
ok the glove has been thrown down...
好吧,手套被扔了……
var elements = (document.getElementsByTagName('li'));
var vals = [];
for(var i=0;typeof(elements[i])!='undefined';vals.push(elements[i++].getAttribute('value')));
no library 3 lines of code...
没有库 3 行代码...
epicly faster
非常快
var myVals = [];
$('li','ul').each(function(){
myVals.push($(this).attr('value'));
});
and using jquery's map function...
并使用 jquery 的地图功能...
var myVals = [];
$('li','ul').map(function(){
myVals.push($(this).attr('value'));
});
and they are both equally as fast..
http://jsperf.com/testing-stuff
他们都同样快..
http://jsperf.com/testing-stuff
回答by natedavisolds
I think that map works just fine.. just not in the chain.
我认为该地图工作得很好......只是不在链中。
var vals = $.map($("li[value]"), function(li) {
return $(li).attr("value");
});
回答by John Green
var outVal = [];
$('ul li').each(function(idx, el){
outVal.push($(this).attr('value'));
});
回答by Nicolas Buduroi
Speaking of elegant code, we can get a better solution using Underscore in combination with jQuery:
说到优雅的代码,我们可以用 Underscore 结合 jQuery 得到更好的解决方案:
_($('ul li').toArray()).map(function(e) { return e.value })
And while we're at it, why not dump Javascript for CoffeeScript:
当我们在做的时候,为什么不为 CoffeeScript 转储 Javascript:
_($('ul li').toArray()).map (e) -> e.value
;-)
;-)