假设点击可以在页面上的任意位置,那么如何通过JavaScript获得点击时的DOM元素属性名称?

时间:2019-06-13 10:39:48

标签: javascript html dom attributes element

假设我有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>```

1 个答案:

答案 0 :(得分:0)

这是执行此操作的代码:

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

它将记录您在控制台上单击的非常元素的属性及其值。

您需要访问他们的密钥。