我怎么知道点击了哪个html元素
问题描述:
我们可以知道用户点击了哪个html。
Can we know which html clicked by user.
答
-SA
听起来像是一个错误的方法。您无需知道单击哪一个,您需要根据用户点击的内容以不同方式处理点击。你看到了区别吗?
所以,你只需为某些元素安装一些处理程序,为其他元素安装一些不同的处理程序:
Sounds like a wrong approach. You don't need to know which one is clicked, you need to handle the click differently depending on what the use clicks. Do you see the difference?
So, you just install some handler for some elements, some different handler for other elements:
function someClickHandler() {
// do something
}
function someOtherHandler() {
// do something else
}
oneElement.onclick = someClickHandler;
anotherElement.onclick = someOtherHandler;
// you can reuse the same handler for more than one element,
// depending on what you need
此外,您可以使用属性 target
传递事件对象并查找目标元素:
Additionally, you can pass event object and find the target element using the property target
:
// do this little experiment:
oneElement.onclick = someClickHandler; // yes, it will work even if the
// handler is not yet defined; want to know why? :-)
function someClickHandler(ev) {
if (ev.target === oneElement)
alert("you passed reference to the element clicked");
}
// use it the way you want