首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用jQuery获取元素的所有属性

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

Stack Overflow用户
提问于 2013-02-01 19:57:43
回答 5查看 199.6K关注 0票数 135

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

代码语言:javascript
复制
$(this).attr().each(function(index, element) {
    var name = $(this).name;
    var value = $(this).value;
    //Do something with name and value...
});

有人能告诉我这是不是可能的,如果是的话,正确的语法是什么?

EN

回答 5

Stack Overflow用户

发布于 2018-04-24 22:54:26

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

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2014-09-20 16:48:20

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

代码语言:javascript
复制
_.transform(this.attributes, function (result, item) {
  item.specified && (result[item.name] = item.value);
}, {});
票数 3
EN

Stack Overflow用户

发布于 2017-05-29 18:46:06

使用javascript函数可以更容易地获取NamedArrayFormat中一个元素的所有属性。

代码语言:javascript
复制
$("#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>");
  });
});
代码语言:javascript
复制
<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>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14645806

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档