【问题标题】:Get all attributes of an element using jQuery使用jQuery获取元素的所有属性
【发布时间】:2013-01-16 17:40:18
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript jquery attributes


    【解决方案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" }
    

    【讨论】:

    • 当没有匹配的元素时,您可能需要修复它,例如$().attr()
    • attributes 集合包含旧版 IE 中所有可能的属性,而不仅仅是那些在 HTML 中指定的属性。您可以通过使用每个属性 specified 属性过滤属性列表来解决此问题。
    • 这是 jQuery .attr() 方法的一个非常好的和预期的功能。奇怪的是 jQuery 不包含它。
    • 有点好奇为什么我们在this[0].attributes中将它作为数组访问?
    • attributes 不是一个数组,但在 Chrome 中至少它是一个 NamedNodeMap,它是一个对象。
    【解决方案2】:

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

    原版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;
        }, {} );
    }
    

    lodash

    比Underscore版本更简洁,但只适用于lodash,不适用于Underscore。需要 IE9+,在 IE8 中有问题。感谢@AlJey for that one

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

    测试页面

    在JS Bin,有一个live test page 涵盖了所有这些功能。测试包括布尔属性(hidden)和枚举属性(contenteditable="")。

    【讨论】:

      【解决方案3】:

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

      function getAttributes ( $node ) {
            $.each( $node[0].attributes, function ( index, attribute ) {
            console.log(attribute.name+':'+attribute.value);
         } );
      }
      
      getAttributes($(this));  // find out what attributes are available
      

      【讨论】:

        【解决方案4】:

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

        _.transform(this.attributes, function (result, item) {
          item.specified && (result[item.name] = item.value);
        }, {});
        

        【讨论】:

          【解决方案5】:

          使用 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>

          【讨论】:

            【解决方案6】:

            Underscore.js 的简单解决方案

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

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

            Working fiddle

            【讨论】:

              【解决方案7】:

              我的建议:

              $.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();

              【讨论】:

                【解决方案8】:

                这是给你的单线。

                JQuery 用户:

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

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

                原版 Javascript 用户:

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

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

                干杯!!

                【讨论】:

                  猜你喜欢
                  • 2011-01-04
                  • 1970-01-01
                  • 1970-01-01
                  • 2010-12-01
                  • 1970-01-01
                  • 2020-08-24
                  • 1970-01-01
                  • 2021-04-17
                  • 2018-01-07
                  相关资源
                  最近更新 更多