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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14645806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:29:47  来源:igfitidea点击:

Get all attributes of an element using jQuery

javascriptjqueryattributes

提问by Styphon

I am trying to go through an element and get all the attributes of that element to output them, for example an tag may have 3 or more attributes, unknown to me and I need to get the names and values of these attributes. I was thinking something along the lines of:

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

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

Could anyone tell me if this is even possible, and if so what the correct syntax would be?

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

回答by pimvdb

The attributesproperty contains them all:

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);
    }
  });
});


What you can also do is extending .attrso that you can call it like .attr()to get a plain object of all attributes:

您还可以做的是扩展,.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);

Usage:

用法:

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

回答by hashchange

Here is an overview of the many ways that can be done, for my own reference as well as yours :) The functions return a hash of attribute names and their values.

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

Vanilla JS:

香草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;
}

Vanilla JS with Array.reduce

带有 Array.reduce 的 Vanilla JS

Works for browsers supporting ES 5.1 (2011). Requires IE9+, does not work in IE8.

适用于支持 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

This function expects a jQuery object, not a DOM element.

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

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

    return attrs;
}

Underscore

下划线

Also works for lodash.

也适用于 lodash。

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

lodash

洛达什

Is even more concise than the Underscore version, but only works for lodash, not for Underscore. Requires IE9+, is buggy in IE8. Kudos to @AlJey for that one.

比 Underscore 版本更简洁,但仅适用于 lodash,不适用于 Underscore。需要 IE9+,在 IE8 中有问题。感谢@AlJey为那一个

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

Test page

测试页

At JS Bin, there is a live test pagecovering all these functions. The test includes boolean attributes (hidden) and enumerated attributes (contenteditable="").

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

回答by zzapper

A debugging script (jquery solution based on the answer above by hashchange)

一个调试脚本(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

回答by Eugene Kuzmenko

with LoDash you could simply do this:

使用 LoDash,您可以简单地执行以下操作:

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

回答by Vishnu Prasanth G

Using javascript function it is easier to get all the attributes of an element in NamedArrayFormat.

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

回答by pymen

Simple solution by Underscore.js

Underscore.js 的简单解决方案

For example: Get all links text who's parents have class someClass

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

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

Working fiddle

工作小提琴

回答by William

My suggestion:

我的建议:

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

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