簡體   English   中英

如何通過JavaScript獲取DOM元素屬性名稱,假設點擊可以在頁面的任何位置?

[英]How can I get DOM elements attributes name on a click, by JavaScript supposing the click can be anywhere on the page?

假設我有html頁面,當用戶點擊頁面時,如果用戶點擊它就會發生事件,應該保存該元素背后的所有屬性。

<head>
<script>
document.addEventListener('click', function(e) {
    e = e || window.event;
    var target = e.target || e.srcElement,
        text = target.textContent || target.innerText;   
}, false);
</script>
</head>
<body>
<p style="color: green">
The content above was created with JavaScript.<br>
This content is created with <b>HTML</b>.<br>
You can edit JavaScript and HTML in the left part of the page
and click "<b>Run code</b>" to view results in the right part of the page.
</p>
<div id="dev1">
<p style="color: green">
The content above was created with JavaScript.<br>
Username : <input type="text" name="txtusername" id="username" > <br><br>
Password : <input type="Password" name="password" id="passname" >
</p>
</div>
<b>LESSON 4: CALL A JAVASCRIPT FUNCTION:</b>
</body>
</html>```

這是執行此操作的代碼:

  document.onclick = function(event) {
    elem = event.target.attributes;
    console.log(event.target.attributes);
    attributes = Object.getOwnPropertyNames(elem);
    console.log(attributes)
  }

它將記錄您在控制台上單擊的元素的屬性及其值。

您需要訪問他們的密鑰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM