javascript - 使用 jQuery 获取元素的所有属性

标签 javascript jquery attributes

我正在尝试遍历一个元素并获取该元素的所有属性以输出它们,例如,一个标签可能有 3 个或更多属性,我不知道,我需要获取这些属性的名称和值。我在想一些事情:

$(this).attr().each(function(index, element) {
    var name = $(this).name;
    var value = $(this).value;
    //Do something with name and value...
});

谁能告诉我这是否可行,如果可行,正确的语法是什么?

最佳答案

attributes 属性包含所有这些:

$(this).each(function() {
  $.each(this.attributes, function() {
    // this.attributes is not a plain object, but an array
    // of attribute nodes, which contain both the name and value
    if(this.specified) {
      console.log(this.name, this.value);
    }
  });
});

你还可以做的是扩展 .attr 这样你就可以像 .attr() 一样调用它来获得所有属性的普通对象:

(function(old) {
  $.fn.attr = function() {
    if(arguments.length === 0) {
      if(this.length === 0) {
        return null;
      }

      var obj = {};
      $.each(this[0].attributes, function() {
        if(this.specified) {
          obj[this.name] = this.value;
        }
      });
      return obj;
    }

    return old.apply(this, arguments);
  };
})($.fn.attr);

用法:

var $div = $("<div data-a='1' id='b'>");
$div.attr();  // { "data-a": "1", "id": "b" }

关于javascript - 使用 jQuery 获取元素的所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14645806/

相关文章:

javascript - 无法删除 Javascript 中 event.data 附加的 jQuery 事件监听器

javascript - 选中复选框后,我需要启用表单(它在页面加载时被禁用)

javascript - 如何重新分配变量并再次运行代码

javascript - 如何从AngularJS指令中获取和设置元素高度

html - 如何对HTML中的图像进行分类并显示通过超链接单击具有给定类别的所有图像

javascript - Javascript函数调用具有可选属性

dictionary - Groovy - 在对象实例化期间忽略映射中的额外属性

javascript弹窗文件永远不会是 "ready"

javascript - 模拟 GraphQL,MockList 仅生成数组中的两项

javascript - 将 "this"传递给自定义 Tap 事件回调的正确方法