![](/img/trans.png)
[英]How to mimic an HTML element and add attributes to it in Javascript/jQuery
[英]How to add and get attributes of html element in Jquery
例如我有這個代碼:
<div class="class1" ng-keydown="ex()">
</div>
如何獲取 div 標簽中的所有這些屬性? 例如,我想使用 jquery 獲取類和 ng-keydown,以及如何使用 jquery 向其添加內容,例如,如果我想向其中添加 ng-mouseclick。
您可以通過$("div")[0].attributes;
獲取所有屬性$("div")[0].attributes;
一個 div
//Get All Attributed of div let attr = $("div")[0].attributes; //Loop thru all attributes $.each(attr, function(e) { if (this.specified) { console.log(this.name + ": " + this.value); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="class1" ng-keydown="ex()"></div>
如果你有多個divs
,你可以做each
循環通過div
s
$("div").each(function() { $.each(this.attributes, function(e) { if (this.specified) { console.log(this.name + ": " + this.value); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="class1" ng-keydown="ex()"></div> <div class="class2" ng-keydown="ex2()"></div> <div class="class3" ng-keydown="ex3()"></div>
使用這個: $('.class1').attr('ng-keydown');
如何獲取 div 標簽中的所有這些屬性?
使用attributes
並reduce
var elem = document.querySelector('div').attributes;
var output = [...elem].reduce( ( a, c ) => ( a[ c.nodeName ] = c.value, a ) , {});
演示
var elem = document.querySelector('div').attributes; var output = [...elem].reduce( ( a, c ) => ( a[ c.nodeName ] = c.value, a ) , {}); console.log( output );
<div class="class1" ng-keydown="ex()"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.