jQuery:从多个元素中检索命名属性

标签 jquery

我有一堆元素希望转换为属性数组,并且我使用以下代码:

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/

相关文章:

html - 下拉菜单仍处于事件状态时菜单项的背景颜色

javascript - Jquery动画循环

javascript - 无法读取未定义的属性 'replace'

javascript - 为什么滚动时音频停止播放?

javascript - 如何使用 JS/Jquery 清除 div 容器的内容?

javascript - 我的动画 gif 在所有浏览器中 2 分钟后停止工作

javascript - JQuery 在鼠标单击时显示和隐藏 div(动画)

当 html 在 JSON 数据包中传递时,Javascript 错误

jQuery 下拉悬停在 Div 上(不仅仅是链接)

jquery - 如何通过 jquery 将 json 响应 Hook 到 html 表单?