Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

javascript - why is jQuery click event firing multiple times

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...