Javascript 单击事件处理程序 - 如何获取对单击项的引用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7846268/
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-08-24 03:48:59  来源:igfitidea点击:

Javascript click event handler - how do I get the reference to the clicked item?

javascripthtmlevent-handlingclick

提问by antonpug

My HTML:

我的 HTML:

<div id="x" onclick="clickHandler(event)">
   <div id="button1">This turns green</div>
   <div id="button2">This turns blue</div>
</div>

So first of all, why am I supposed to be passing "event" into the click handler and is event some kind of system keyword? Also, since the click handler is identified on the container div, how do I know which button has been clicked?

所以首先,为什么我应该将“事件”传递给点击处理程序,并且事件是某种系统关键字?另外,由于单击处理程序是在容器 div 上标识的,我怎么知道哪个按钮被单击了?

回答by James Allardice

eventis an Event object which is created automatically when an event is fired. Note that you don't have to call it event(I tend to call it simply e). That Event object has a number of properties which describe the event it represents. In this case, the one you're interested in would be target, which shows the element that was the source of the event:

event是在触发事件时自动创建的 Event 对象。请注意,您不必调用它event(我倾向于简单地调用它e)。该 Event 对象具有许多描述它所代表的事件的属性。在这种情况下,您感兴趣的将是target,它显示作为事件源的元素:

function clickHandler(e) {
    var target = e.target;
}

Here's a working example.

这是一个工作示例

Unfortunately, it's never quite that simple. While the specification says it should be event.target, Internet Explorer likes to be different, and chooses to use event.srcElement, so you probably want to put in a check to make sure event.targetexists! For example:

不幸的是,事情从来没有那么简单。虽然规范说它应该是event.target,但 Internet Explorer 喜欢与众不同,并选择使用event.srcElement,因此您可能需要进行检查以确保event.target存在!例如:

function clickHandler(e) {
    var target = (e.target) ? e.target : e.srcElement;
}

回答by Pete Wilson

I usually just name the clicked element in the argument list of the call to the click handler, something like (untested) this:

我通常只是在调用单击处理程序的参数列表中命名被单击的元素,例如(未经测试):

<div id="x">
   <div id="button1" onclick="handle_click_event( this, 'green' )">This turns green</div>
   <div id="button2" onclick="handle_click_event( this, 'blue' )">This turns blue</div>
</div>

function handle_click_event ( obj, new_color ) {
  obj.style.backgroundColor = new_color;
}

Could that approach work for you?

这种方法对你有用吗?

回答by yeeen

Why can't you do this?

为什么你不能这样做?

<div id="x">
   <div id="button1" onclick="clickHandler1()">This turns green</div>
   <div id="button2" onclick="clickHandler2()">This turns blue</div>
</div>