A quick fix for repeated binding of jquery events

  • 2020-03-30 01:13:48
  • OfStack

One $.fn.live duplicate bind

Solution: With the die() method, all previously bound events on this element are unbound before the live() method is bound, and new events are bound via the live() method.

//The die() method is unbound, followed by the live() binding
$( " #selectAll " ).die().live( " click " ,function(){
//Event run code

Two click and other events

Solution: Use the unbind("click") method to unbind the bound event and then bind the new event, which removes the original event on the object before binding the event to it

Complete test code:

<div class="box">
            <button id="test"> Duplicate binding triggers the button </button>( Click this button twice or more , You can trigger a repeat binding , Click the button below again to see the result )
            <button id="test1">click Repeat the bind test button </button>
            <button id="test2">click Bind the test button once </button>
            <button id="test3">live Repeat the bind test button </button>
            <button id="test4">live Bind the test button once </button>
        <script type="text/javascript" src="../static/jquery-1.6.1.min.js"></script>
        <script type="text/javascript">
                var i = 1,j=1,k=1,h=1,n=1;
                var triggerBind = function(){
                    $("#test1").click(function() {
                        alert("click Unbound repeat bound execution " + j++ + " time ");
                    $("#test2").unbind('click').click(function() {
                        alert("click Unbound execution " + k++ + " time ");

                    $("#test3").live("click",function() {
                        alert("live Unbound repeat execution " + h++ + " time ");
                    $("#test4").die().live("click",function() {
                        alert("live Execute after unbinding " + n++ + " time ");
                $("#test").click(function() {
                    alert(" To trigger the binding, click "first" " + i++ + " time ");

Related articles: