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 - 当 Internet Explorer 开发人员工具栏可见时,注销仅适用于 Internet Explorer(11)

javascript - jQuery 搜索和替换不起作用(Wordpress)

jQuery 选择器问题

c# - 如何从 WebBrowser 组件获取 HTMLElement 的所有属性

javascript - 如果用户不与当前通知交互,则后续的 Chrome 扩展通知 onAlarm 将不再显示

javascript - 似乎无法在 Google Web App Script 中将多个参数从 JS 传递到 HTML

jquery - 使用 jQuery 进行 HTML5 验证?

javascript - 选择器在我的网站上解释为 HTML。攻击者可以轻易利用它吗?

xsd - 将属性设置为 XML 模式中的所有类型

c# - 将 [Serializable] 添加到类中是否会对性能产生影响?