当点击html标签时,Jquery点击事件触发两次 [英] Jquery click event triggers twice when clicked on html label

查看:585
本文介绍了当点击html标签时,Jquery点击事件触发两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div容器,其中包含html复选框及其标签。
使用jquery我想触发一个点击事件,当有人点击这个容器中的标签。

I have an div container which contains html checkbox and its label. Using jquery i wanted to trigger an click event when someone clicks on label in this container.

我看到jquery点击事件触发两次,当我点击标签!

I see that jquery click event triggers twice when i click on label!

为了测试目的,我在复选框而不是标签
上触发了点击事件,这里的复选框点击事件触发器只有一次。

For testing purpose i triggered click event on checkbox instead of label and here checkbox click event triggers only once as it should be.

这里是小提琴。
http://jsfiddle.net/AnNvJ/2/

<tr>
    <td>
        <div id="test">
            <label>
                <input type="checkbox" id="1" />demo1</label>
            <label>
                <input type="checkbox" id="2" />demo2</label>
            <label>
                <input type="checkbox" id="3" />demo3</label>
        </div>
    </td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
</tr>

JQUERY

$(document).ready(function () {

    $('#test label').live('click', function (event) {
        alert('clicked');
    });


    $('#test checkbox').live('click', function (event) {
        alert('clicked');
    });

});


推荐答案

$ '#test checkbox')从未被调用,因为您没有名为复选框的标签。

The one of $('#test checkbox') is never called, because you don't have an tag with name checkbox.

取决于你点击复选框还是标签, $('#test label')的回调被调用一次或两次因为输入元素是标签的一部分并且是一个 union ,因此也接收到事件,如果标签是点击的(不是冒泡,你不能做 event.stopPropagation())。

And depending if you click on checkbox or the label, the callback for $('#test label') is called once or twice cause of the bubbling because the input element is part of the label and is one union and therefor also received the event if the label is click (is is not bubbling, you can't do event.stopPropagation()).

如果您以这种方式更改代码, >

You can check this if you change your code this way:

 $('#test label').live('click', function (event) {
        event.stopPropagation(); //<-- has no effect to the described behavior
        console.log(event.target.tagName);
 });

点击标签:


LABEL

INPUT

LABEL
INPUT

点击输入:


INPUT

INPUT

EDIT
您只需要处理对标签的点击,而不是复选框 - 您不能更改您的html结构 - 您只需忽略 输入

EDIT If you only want to handle the click on the label and not the checkbox - and you can't change you html structure - you can just ignore the event of the input element.

$('#test label').live('click', function (event) {
    if( event.target.tagName === "LABEL" ) {
         alert('clicked');
    }
});

或使用jQuery测试:

Or using jQuery to test:

$('#test label').live('click', function (event) {
    if( $(event.target).is("label") ) {
         alert('clicked');
    }
});

这篇关于当点击html标签时,Jquery点击事件触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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