135

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

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

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

4

8 回答 8

261

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" }
于 2013-02-01T11:58:58.463 回答
28

以下是可以完成的许多方法的概述,供我自己参考以及您的参考:) 这些函数返回属性名称及其值的哈希值。

香草JS

function getAttributes ( node ) {
    var i,
        attributeNodes = node.attributes,
        length = attributeNodes.length,
        attrs = {};

    for ( i = 0; i < length; i++ ) attrs[attributeNodes[i].name] = attributeNodes[i].value;
    return attrs;
}

带有 Array.reduce 的香草 JS

适用于支持 ES 5.1 (2011) 的浏览器。需要 IE9+,在 IE8 中不起作用。

function getAttributes ( node ) {
    var attributeNodeArray = Array.prototype.slice.call( node.attributes );

    return attributeNodeArray.reduce( function ( attrs, attribute ) {
        attrs[attribute.name] = attribute.value;
        return attrs;
    }, {} );
}

jQuery

这个函数需要一个 jQuery 对象,而不是 DOM 元素。

function getAttributes ( $node ) {
    var attrs = {};
    $.each( $node[0].attributes, function ( index, attribute ) {
        attrs[attribute.name] = attribute.value;
    } );

    return attrs;
}

下划线

也适用于 lodash。

function getAttributes ( node ) {
    return _.reduce( node.attributes, function ( attrs, attribute ) {
        attrs[attribute.name] = attribute.value;
        return attrs;
    }, {} );
}

罗达什

比 Underscore 版本更简洁,但仅适用于 lodash,不适用于 Underscore。需要 IE9+,在 IE8 中有问题。向@AlJey致敬

function getAttributes ( node ) {
    return _.transform( node.attributes, function ( attrs, attribute ) {
        attrs[attribute.name] = attribute.value;
    }, {} );
}

测试页面

在 JS Bin,有一个涵盖所有这些功能的实时测试页面。测试包括布尔属性 ( hidden) 和枚举属性 ( contenteditable="")。

于 2016-07-27T21:54:41.523 回答
4

一个调试脚本(基于 hashchange 上面答案的 jquery 解决方案)

function getAttributes ( $node ) {
      $.each( $node[0].attributes, function ( index, attribute ) {
      console.log(attribute.name+':'+attribute.value);
   } );
}

getAttributes($(this));  // find out what attributes are available
于 2018-04-24T14:54:26.400 回答
3

使用 LoDash 你可以简单地做到这一点:

_.transform(this.attributes, function (result, item) {
  item.specified && (result[item.name] = item.value);
}, {});
于 2014-09-20T08:48:19.763 回答
0

使用 javascript 函数可以更轻松地获取 NamedArrayFormat 中元素的所有属性。

$("#myTestDiv").click(function(){
  var attrs = document.getElementById("myTestDiv").attributes;
  $.each(attrs,function(i,elem){
    $("#attrs").html(    $("#attrs").html()+"<br><b>"+elem.name+"</b>:<i>"+elem.value+"</i>");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="myTestDiv" ekind="div" etype="text" name="stack">
click This
</div>
<div id="attrs">Attributes are <div>

于 2017-05-29T10:46:05.937 回答
0

Underscore.js 的简单解决方案

例如:获取所有链接文本谁的父母有课someClass

_.pluck($('.someClass').find('a'), 'text');

工作小提琴

于 2018-11-10T09:47:49.950 回答
0

这是给你的单线。

jQuery 用户:

替换$jQueryObject为您的 jQuery 对象。即$('div')

Object.values($jQueryObject.get(0).attributes).map(attr => console.log(`${attr.name + ' : ' + attr.value}`));

原版 Javascript 用户:

替换$domElement为您的 HTML DOM 选择器。即document.getElementById('demo')

Object.values($domElement.attributes).map(attr => console.log(`${attr.name + ' : ' + attr.value}`));

干杯!!

于 2020-10-21T09:50:43.157 回答
0

我的建议:

$.fn.attrs = function (fnc) {
    var obj = {};
    $.each(this[0].attributes, function() {
        if(this.name == 'value') return; // Avoid someone (optional)
        if(this.specified) obj[this.name] = this.value;
    });
    return obj;
}

var a = $(el).attrs();

于 2019-03-28T15:41:44.777 回答