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

跟風遠走 提交于 2019-11-26 13:03:43

问题


My 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?


回答1:


event is 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:

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.target exists! For example:

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



回答2:


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?




回答3:


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>


来源:https://stackoverflow.com/questions/7846268/javascript-click-event-handler-how-do-i-get-the-reference-to-the-clicked-item

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