Javascript 全局 onclick 侦听器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29555044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:43:09  来源:igfitidea点击:

Javascript global onclick listener

javascripthtml

提问by Bogdan Zurac

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.

有没有办法注册一个全局 onclick 侦听器,该侦听器将在单击元素时触发?还需要获取该元素的 id。

回答by emd

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

回答by ketan

You can get id this way using javascript:

您可以使用 javascript 以这种方式获取 id:

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" />