Javascript点击事件处理程序 - 如何获取对点击的项目的引用? [英] Javascript click event handler - how do I get the reference to the clicked item?

查看:85
本文介绍了Javascript点击事件处理程序 - 如何获取对点击的项目的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的HTML:

<div id="x" onclick="clickHandler(event)">
   <div id="button1">This turns green</div>
   <div id="button2">This turns blue</div>
</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?

推荐答案

p> 事件是一个事件对象,它在触发事件时自动创建。请注意,您不必将其称为事件(我倾向于简单地称之为 e )。该事件对象具有描述其表示的事件的许多属性。在这种情况下,您感兴趣的是目标,其中显示了事件来源的元素:

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;
}

这是一个工作示例

不幸的是,它从来没有那么简单。虽然规范说应该是 event.target ,但Internet Explorer喜欢不同,并选择使用 event.srcElement ,所以你可能想放一个检查,以确保 event.target 存在!例如:

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;
}

这篇关于Javascript点击事件处理程序 - 如何获取对点击的项目的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆