当按下带有html标签的html按钮时,目标错误 [英] Wrong target when pressing html button with html tags in it

查看:158
本文介绍了当按下带有html标签的html按钮时,目标错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有四个按钮,想跟踪哪一个被按下。在其中一些我用HTML标签更改了innerHTML属性。然后我注意到当按下一个按钮时,mouseEvent.target可能不是按钮而是文本本身。这仅在按下html-tag-modified按钮时发生。

I have four buttons and want to trace which one is pressed. In some of them I changed innerHTML property with HTML tag. Then I noticed that when a button is pressed there is a possability of mouseEvent.target being not a button but the text itself. This only occures when html-tag-modified button is pressed.

以下是js代码的一部分:

Here is a part of the js code:

for (var i = 0; i < 4; i++){        
    buttons[i].innerHTML = countries[index]["c"];
    buttons[i].onclick = clickHandler;

}

buttons[correct_btn].innerHTML = "<some-tag>" + countries[target_id]["c"] + "</some-tag>";

function clickHandler(me){
    console.log(me.target);
}

我希望我能清楚地描述这个问题。我可以在按钮中没有html标签的情况下离开,但我仍然想知道是否有办法避免按钮文本被定位。或者可能是我从一开始就错误地追踪按钮的方法?

I hope I described the problem clearly. I could get away without html tag in buttons, but I still wonder if there is a way to avoid button text being targeted. Or could it be that my approach to trace buttons wrong from the beginning?

推荐答案

使用 currentTarget 。来自MDN:


它始终引用事件处理程序附加到
的元素,而不是event.target标识
事件发生的元素

It always refers to the element the event handler has been attached to as opposed to event.target which identifies the element on which the event occurred



function clickHandler(me){
    console.log(me.currentTarget);
}

这里是演示上述内容的小提琴。

Here is a fiddle to demonstrate the above.

这篇关于当按下带有html标签的html按钮时,目标错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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