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

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

问题描述

我遇到的问题非常类似于: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);

单击文本(Up Vote!或Down Vote!)会产生以下控制台输出:

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

即使我已经使用选择器按钮注册了元素上的句柄。投票按钮。有谁知道为什么会发生这种情况?我讨厌必须给图标提供数据属性。

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.

推荐答案

它是由事件传播引起的。你点击按钮内的图标,所以点击事件通过DOM从图标传播到按钮,一直以来o文件。这导致您的点击正在执行的事件处理程序代码。

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.

如果问题是你只是想要在每次代码运行时引用该按钮,但是当你单击图标而不是文本时仍然希望它被触发,你只需要使用这个而不是比 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将确保总是引用按钮,即使实际的 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天全站免登陆