简体   繁体   English

如何获取调用者事件和dom元素id

[英]How to get the caller event and dom element id

<script>
function Hello(){
    var caller =  arguments.callee.caller;
    alert( caller );
}
</script>

<input type="button" id="btnHello" value="Hello" onclick="Hello()" />

How to get the button id from the the Hello function above with out passing the any argument in the Hello function 如何从上面的Hello函数中获取按钮id,而不传递Hello函数中的any参数

An event object is passed to the Hello function automatically. 事件对象自动传递给Hello函数。 You need to receive it as an argument and then do some cross-platform work to grab the element. 您需要将其作为参数接收,然后执行一些跨平台工作来获取元素。 A JS framework will help you out here. JS框架将在这里帮助您。

function Hello(e){
    var caller = e.target || e.srcElement;
    console.log( caller );
}

EDIT 编辑
+1 Andrew's comment below. +1安德鲁的评论如下。 Use addEventListener and attachEvent for best practice. 使用addEventListener和attachEvent进行最佳实践。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM