在href点击获取html节点

The*_*per -4 html javascript jquery html5 dom

在我的html页面中,我希望在其href点击上获得html节点.

例:

HTML文件

<!DOCTYPE html>
<html>
<body>

<p><a href="https://www.w3schools.com/html/" data-type="W3">Click1</a></p>
<p><a href="https://www.google.com/html/" data-type="google">Click2</a></p>


</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Click1被点击我要值:W3Click2点击我要值:google

目前,我document.documentElement.outerHTML用来获取完整的html字符串并解析它.有没有更好的方法来获得data-typehref点击的价值?

j08*_*691 5

jQuery的:

$('a').click(function(){ console.log( $(this).data('type') ) })
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

var link = document.querySelectorAll('a');
for (var i = 0; i < link.length; i++) {
  link[i].addEventListener('click', function(e) {
    console.log(this.dataset.type)
  });
}
Run Code Online (Sandbox Code Playgroud)