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被点击我要值:W3
当Click2点击我要值:google
目前,我document.documentElement.outerHTML用来获取完整的html字符串并解析它.有没有更好的方法来获得data-typehref点击的价值?
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)