为什么jQuery点击事件触发多次 [英] why is jQuery click event firing multiple times

查看:65
本文介绍了为什么jQuery点击事件触发多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有这个示例代码
http://jsfiddle.net/DBBUL/10/

  $(document).ready(function($){

$(' ()函数(){

$('#confirmCreateModal')。modal();

$('#confirmCreateYes')。click(function (){
$('#confirmCreateModal')。modal('hide');

var test =123;
alert(test);
console.log(test);
});
});
});

如果您单击创建按钮3次,并且每次在确认中单击是点击创建按钮3次,每次点击否,第4次点击是时,点击对于之前的每次点击,都会触发警报,而不是一次。



这种行为对我来说似乎很奇怪,因为我希望每次点击一次就会触发警报。我必须使用.unbind()还是有更好的解决方案?



有人可以告诉我为什么会发生这种情况,以及如何解决它?



谢谢

解决方案

因为你绑定了多次。单击事件中的单击事件意味着每次单击时,都会在先前绑定的事件之上绑定新的单击事件。除非点击事件创建元素,否则不要在点击事件内绑定点击事件。

  $(document).ready(function($){ 

$('#confirmCreateModal')。modal({show:false});

$('#secureCreateYes')。click(function(){
$ b'('#confirmCreateModal')。modal('hide');

var test =123;
alert(test);
console.log(test) ;
$)
$ b $('。creategene')。click(function(){

$('#confirmCreateModal')。modal('show ');

});
}); b


$ b

noreferrer>演示

I have this sample code here http://jsfiddle.net/DBBUL/10/

    $(document).ready(function ($) {

    $('.creategene').click(function () {

        $('#confirmCreateModal').modal();

        $('#confirmCreateYes').click(function () {
            $('#confirmCreateModal').modal('hide');

            var test = "123";
            alert(test);
            console.log(test);             
        });
    });
});

If you click the create button 3 times and each time you click yes on the confirmation, the alert is fired multiple times for each click instead of just one time.

If you click the create button 3 times and each time you click no and on the 4th time you click yes the alert is fired for each of the previous clicks instead of just one time.

this behavior seems weird to me as i would expect the alert to be fired once per click. Do I have to use .unbind() or is there a better solution?

Could someone please tell me why this is happening and how to fix it?

Thanks

解决方案

Because you are binding it multiple times. Click event inside a click event means every time you click, a new click event is being bound on top of the previously bound events. Do not bind click events inside of click events unless the click event creates the element. There's also no need to re-initialize the modal over and over.

$(document).ready(function ($) {

    $('#confirmCreateModal').modal({show: false});

    $('#confirmCreateYes').click(function () {
        $('#confirmCreateModal').modal('hide');

        var test = "123";
        alert(test);
        console.log(test);             
    });

    $('.creategene').click(function () {

        $('#confirmCreateModal').modal('show');

    });
});

Demo

这篇关于为什么jQuery点击事件触发多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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