简体   繁体   English

防止多个事件触发

[英]Prevent multiple event triggering

I am here again 我又在这里

SEE DEMO HERE 在此处查看演示

$(document).ready(function () {

    $("#id_priori").on('click', 'li', function(){
        var self = $(this),
            checkbox = self.find(":checkbox")[0];

        checkbox.checked = !checkbox.checked;

        self.toggleClass( 'on', checkbox.checked );
    }).find(":checkbox").each(function(){
       $(this).closest('li').toggleClass('on', this.checked);
    });

    $("#id_tipo").on('click', 'li', 'label', function () {
        var self = $(this),
            radio = self.find(":radio")[0];

        radio.checked = !radio.checked

        $(":radio:not(checked)").each(function () {
            $(this).closest('li').toggleClass("on", this.checked);
        });

    })
        .find(":radio").each(function () {
        $(this).closest('li').toggleClass('on', this.checked);
    });

}); });

Everything works fine but for the labels , when I click them they dont check , doing a little tweaks it seems like one event is triggrering multiple times and it unchecks them , try setting an alert and you'll see what I mean 一切正常,但对于标签,当我单击它们时,它们没有检查,做了一些微调,似乎一个事件多次触发,并且取消了它们,尝试设置警报,您会明白我的意思了

Any idea whats wrong ? 知道有什么问题吗?

Because you're taking over the role of the actual input you need to allow the input element to carry on with its own behavior ( http://jsfiddle.net/icodeforlove/rF2FT/2/ ) 因为您要接管实际输入的角色,所以需要允许输入元素继续自身的行为( http://jsfiddle.net/icodeforlove/rF2FT/2/

if (event.target === checkbox) return;

All you need to do is return early if the target is the actual input element. 您需要做的就是如果目标是实际的输入元素,请尽早返回。 Right now the input element is checking itself and then you're telling it to uncheck itself. 现在,input元素正在对其进行检查,然后您要告诉它取消对其进行检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM