按钮上的点击事件正在发送一个图标作为目标? [英] Click event on button is sending an icon as the target?

查看:16
本文介绍了按钮上的点击事件正在发送一个图标作为目标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题非常类似于:"Jquery当图标位于按钮上时,点击"不会触发" 但是该帖子的分辨率并没有为我提供解决方案,所以我认为可能会发生一些不同的事情.

I am having an issue very similar to: "Jquery 'click' not firing when icon is on button" however the resolution for that post is not providing a solution for me, so I think something different may be going on.

本质问题是我有一个带有图标的按钮.当我点击按钮(例如文本)时,事件目标是按钮元素;但是,当我单击图标时,事件目标是图标对象.不幸的是,这非常烦人,因为我将数据值存储在我想要访问的按钮上.

The essential problem is that I have a button with an icon in it. When I click on the button (e.g. the text) the event target is the button element; however when I click on the icon, the event target is the icon object. This unfortunately is extremely annoying as I am storing data values on my button that I would like access to.

这是 HTML:

<button class="btn btn-success vote-button" id="btnUpVote" type="button" data-vote="1">
    <i class="fa fa-thumbs-up"></i>
    Up Vote!
</button>

<button class="btn btn-danger vote-button" id="btnDownVote" type="button" data-vote="-1">
    <i class="fa fa-thumbs-down"></i>
    Down Vote!
</button>

这是Javascript:

And here is the Javascript:

function sendVote(event) {
    var $btn = $(event.target);
    console.log(parseInt($btn.data('vote'));
    console.log($btn.prop('tagName'));
}

$('body').on('click', 'button.vote-button', sendVote);

单击文本(赞成票!"或反对票!")会产生以下控制台输出:

Clicking on the text ("Up Vote!" or "Down Vote!") results in the following console output:

1
BUTTON
-1 
BUTTON

单击图标(等)会产生以下控制台输出:

Clicking on the icon (, etc.) results in the following console output:

NaN
I
NaN
I

即使我已经使用选择器button.vote-button"注册了元素的句柄.有谁知道为什么会这样?我不想为图标提供数据属性.

Even though I've registered the handle on elements with selector "button.vote-button". Does anyone know why this is happening? I'd hate to have to give data attributes to the icons.

推荐答案

它是由事件传播引起的.您单击按钮内的图标,因此 click 事件通过 DOM 从图标向上传播到按钮,一直到文档.这会导致您的 click 事件处理程序代码被执行.

It's caused by event propagation. You click on the icon, which is inside the button, so the click event propagates up through the DOM from the icon, to the button, all the way up to the document. This results in your click event handler code being executed.

如果问题是您只想在每次代码运行时引用按钮,但您仍然希望在单击图标而不是文本时触发它,则只需使用 this 而不是 event.target:

If the issue is that you just want the reference to the button every time that code runs, but you still want it to trigger when you click on the icon instead of the text, you just need to use this rather than event.target:

var $btn = $(this);
...

jQuery 将确保 this 始终引用按钮,即使实际的 event.target 元素是其中的一个元素.

jQuery will make sure that this always refers to the button, even if the actual event.target element is an element inside it.

这篇关于按钮上的点击事件正在发送一个图标作为目标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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