开发者

How to get the invoking node in Javascript?

开发者 https://www.devze.com 2023-01-25 07:25 出处:网络
Given function act() in the JavaScript and <p id=\"one\" onclick=\"act()\">, <p id=\"two\" onclick=\"act()\">, can I get to know the p, which has been pressed without using onclick=\"act(t

Given function act() in the JavaScript and <p id="one" onclick="act()">, <p id="two" onclick="act()">, can I get to know the p, which has been pressed without using onclick="act(this)"?开发者_如何学Go Thanks


No, you can't.

You need to pass this (or event, which contains source information).
If you want to, you can write act.call(this), which will call the function in the context of the element, so that this inside act will refer to the element.

Although some browsers also expose the event object as a global, not all browsers do this, so you cannot rely on this behavior.


Actually, it is possible:

<button onclick="called()" id="one">click</button>
<script>
function called()
{
    console.log(window.event);
}
</script>

Trawl around inside window.event to find the targeted element, event type, and other info

0

精彩评论

暂无评论...
验证码 换一张
取 消