繁体   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