我有一堆元素希望转换为属性数组,并且我使用以下代码:
var attributes = [];
$("#id").find("tag").each(function() {
attributes.push($(this).attr("attribute"));
});
有没有更简洁的方法来做到这一点?感觉就像我在用剪刀修剪指甲。
我最近一直在使用d3
,感觉可能有一种方法可以以类似于var attribute = $("#id")的方式来做到这一点。 find("tag").attr("attribute");
但这只是将变量设置为选择中第一个元素的属性。
最佳答案
您可以使用.map()
与 .get()
Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
var attributes = $("#id tag").map(function() {
return $(this).attr("attribute");
}).get();
关于jQuery:从多个元素中检索命名属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37251400/