javascript 如何从 jQuery 对象中的元素获取属性值数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9647968/
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
How to get an array of attribute value from elements in a jQuery object
提问by garyM
I use a custom attribute in elements with my own class. I'm trying to return the value of custom attribute for all elements of the class.
我在具有我自己的类的元素中使用自定义属性。我正在尝试为类的所有元素返回自定义属性的值。
I used jQuery to find the elements by class, and jQuery places the object in an array.
我使用 jQuery 按类查找元素,jQuery 将对象放入数组中。
var tabs = $('li.tab_item');
Now that I'd have the objects in an array, I would like to return the value for the custom attribute for all the array's members.
现在我已经将对象放在一个数组中,我想返回所有数组成员的自定义属性的值。
How can this be done?
如何才能做到这一点?
回答by Tomalak
var tab_attribs = $('li.tab_item').map(function () {
return $(this).attr("custom_attribute");
});
This will give you an array of the custom attribute values. Of course, you can do this more traditionally:
这将为您提供自定义属性值的数组。当然,您可以更传统地执行此操作:
var tab_attribs = [];
$('li.tab_item').each(function () {
tab_attribs.push( $(this).attr("custom_attribute") );
});
Anyway, you should probably make use of the data-*
attributes that HTML5 provides:
无论如何,您可能应该使用data-*
HTML5 提供的属性:
<li class="tab_item" data-foo="some custom data">
and (see jQuery data()
):
和(见jQuerydata()
):
$('li.tab_item').data("foo"); // -> "some custom data"
回答by gilly3
Use .map()
:
使用.map()
:
$("li.tab_item").map(function (){
return this.getAttribute("myAttribute");
});
That gives you an Array of values wrapped in a jQuery object. If you want to get the Array, call .get()
, ie .map(...).get()
.
这为您提供了一个包含在 jQuery 对象中的值数组。如果您想获取数组,请调用.get()
,即.map(...).get()
。
By the way, you can also select the elements by attribute instead of class:
顺便说一句,您还可以通过属性而不是类来选择元素:
$("[myAttribute]")
This will return all elements on the page that have a myAttribute
attribute.
这将返回页面上具有myAttribute
属性的所有元素。
回答by Ali Soltani
Simple solution (ES6)
简单的解决方案(ES6)
Array.from(document.getElementsByClassName('tab_item')).map(item => item.getAttribute('foo'));