Javascript global onclick listener

匿名 (未验证) 提交于 2019-12-03 03:03:02

问题:

Is there a way to register a global onclick listener that will fire anytime an element is clicked? Need to also get the id of that element.

回答1:

document.addEventListener("click", function(evnt){     console.log(evnt.target.id); }); 


回答2:

You can get id this way using javascript:

window.onclick = function(event) {alert(event.target.id);}
<div id="dID">div</div> <button id="bId">Button</button>  <input type="text" id="txtId" class="txtclass" />


回答3:

here is a fiddle

var everything = document.querySelectorAll("body *"); //select every element in the body  Array.prototype.forEach.call(everything, function(el){      el.onclick = function(){         var id = this.id;         console.log(id);     } }); 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!