我在我自己的类的元素中使用了一个自定义属性。我尝试为类的所有元素返回自定义属性的值。
我使用jQuery按类查找元素,然后jQuery将对象放在一个数组中。
var tabs = $('li.tab_item');
现在我已经将对象放入数组中,我想返回数组中所有成员的自定义属性的值。
如何做到这一点?
发布于 2012-03-11 00:21:22
var tab_attribs = $('li.tab_item').map(function () {
return $(this).attr("custom_attribute");
});
这将为您提供一个自定义属性值的数组。当然,您可以更传统地这样做:
var tab_attribs = [];
$('li.tab_item').each(function () {
tab_attribs.push( $(this).attr("custom_attribute") );
});
无论如何,您可能应该利用HTML5提供的data-*
属性:
<li class="tab_item" data-foo="some custom data">
和(参见jQuery data()
):
$('li.tab_item').data("foo"); // -> "some custom data"
发布于 2012-03-11 00:21:52
使用.map()
$("li.tab_item").map(function (){
return this.getAttribute("myAttribute");
});
这为您提供了一个包装在jQuery对象中的值数组。如果你想获取数组,调用.get()
,即.map(...).get()
。
顺便说一下,您还可以按属性而不是按类选择元素:
$("[myAttribute]")
这将返回页面上具有myAttribute
属性的所有元素。
发布于 2018-05-09 22:04:26
Simple solution (ES6)
Array.from(document.getElementsByClassName('tab_item')).map(item => item.getAttribute('foo'));
https://stackoverflow.com/questions/9647968
复制相似问题