search

Home  >  Q&A  >  body text

javascript - js cancel event binding

Use addEvent to bind click events multiple times to an element. Is there any way to cancel all bound events at once?

黄舟黄舟2825 days ago665

reply all(3)I'll reply

  • 为情所困

    为情所困2017-05-19 10:44:35

    removeevent

    reply
    0
  • ringa_lee

    ringa_lee2017-05-19 10:44:35

    No, you can only remove bindings one by one, DOM level 2 is removeEventListener,IE中的是attachEvent.
    Anonymous functions cannot be unbound, so only named functions can be unbound.

    There is a way in JQuery to remove all event handlers at once:

        <input type="button" id="btn" value="Click Me!" name="">
        <input type="button" value="删除所有事件" id="delAll" name="">
        <p id="test">
            
        </p>
    
        $(function(){
            $("#btn").bind("click",function(){
                $("#test").append("<p>我的绑定函数1</p>");
            }).bind("click",function(){
                $("#test").append("<p>我的绑定函数2</p>");
            }).bind("click",function(){
                $("#test").append("<p>我的绑定函数3</p>");
            });
            $("#delAll").bind("click",function(){
                $("#btn").unbind("click");
            })
        })

    In JQ, unbind can be used to unbind all bindings:

    1. If there are no parameters, delete all bound events.

    2. If an event type is provided, only bound events of that type will be deleted.

    3. If the processing function passed when binding is used as the second parameter, only this function will be removed.

    ==================================================== =========
    This is the only method I can think of for now, I hope it helps!

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-19 10:44:35

    element.addEventListener("mouseover", myFunction); Bind event

    element.removeEventListener("mousemove", myFunction); Remove bound event

    Cross-browser compatible solution

    var x = document.getElementById("myBtn");
    if (x.addEventListener) { // All major browsers, except IE 8 and earlier

    x.addEventListener("click", myFunction);

    } else if (x.attachEvent) { // IE 8 and earlier

    x.attachEvent("onclick", myFunction);

    }

    reply
    0
  • Cancelreply