我怎么知道点击了哪个html元素 [英] How can I know which html element clicked

查看:300
本文介绍了我怎么知道点击了哪个html元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以知道用户点击了哪个html。

Can we know which html clicked by user.

推荐答案

听起来像是一个错误的方法。您无需知道单击哪一个,您需要根据用户点击的内容以不同方式处理点击。你看到了区别吗?



所以,你只需为某些元素安装一些处理程序,为其他元素安装一些不同的处理程序:

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





-SA


这篇关于我怎么知道点击了哪个html元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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