我试图遍历一个元素,并获取该元素的所有属性以输出它们,例如,一个标签可能有3个或更多属性,我不知道,我需要获取这些属性的名称和值。我在想一些类似的事情:
$(this).attr().each(function(index, element) {
var name = $(this).name;
var value = $(this).value;
//Do something with name and value...
});
有人能告诉我这是不是可能的,如果是的话,正确的语法是什么?
发布于 2018-04-24 22:54:26
一个调试脚本(基于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
发布于 2014-09-20 16:48:20
使用LoDash,您可以简单地执行以下操作:
_.transform(this.attributes, function (result, item) {
item.specified && (result[item.name] = item.value);
}, {});
发布于 2017-05-29 18:46:06
使用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>
https://stackoverflow.com/questions/14645806
复制相似问题