jquery use on () method binding event is executed multiple times in question

After using jQuery on () method to bind the event, during code execution, you may experience an event is executed twice.

Originally I thought it was an event bubbling problem, later found to be on () method of the characteristic problems caused.

Simple question about the reduction scenarios

Here's a simple question about the reduction scenario, use a button to another button through on () method binding event.

HTML part

< The INPUT the above mentioned id = "bindEventBtn" of the type = "the Button" value = "button to button binding event"  /> 
< the INPUT the above mentioned id = "noEmotionBtn" of the type = "the Button"   value = "I am an emotional button Maude"  / >

JavaScript part

$(function(){
    $('#bindEventBtn').click(function () {
        $('#noEmotionBtn').on('click', function () {
            Alert ( 'I have a feeling Mo button' );
        });
    });
})

Thus, when multiple clicks bindEventBtn button, it will bind to the same event multiple times on noEmotionBtn button.

And a feature on () method is bound to trigger many times how many times, that's the problem.

Solution to the problem

There are two solutions to the problem, in general is bound to be repeated event unbundling.

1. OFF () method unbundling.

$('#noEmotionBtn').off('click').on('click', function () {
    Alert ( 'I have a feeling Mo button' );
});

2. Use the unbind () method unbundling.

$('#noEmotionBtn').unbind('click').on('click', function () {
    Alert ( 'I have a feeling Mo button' );
});

to sum up

The actual scenes may be much more complex, so when using the on () method to the element binding events to pay particular attention to the issue repeatedly binding.

But to solve the problem of the general idea is the same, unified first suggestion is to use the event to unbundle off () method to avoid making mistakes.

Of course, it is best to find the root causes, that is, avoiding multiple binding events happen.

In addition, if the binding element to give a different event handlers in multiple places, it may be necessary to think of another way.

 

"When a person hard to create something, it will have a soul."

Guess you like

Origin www.cnblogs.com/yanggb/p/11345188.html