小编典典

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

javascript

我试图遍历一个元素并获取该元素的所有属性以输出它们,例如,一个标签可能具有3个或更多属性,我不知道,我需要获取这些属性的名称和值。我在考虑以下方面:

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

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


阅读 4211

收藏
2020-05-01

共1个答案

小编典典

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" }
2020-05-01