jquery prevent duplicate function assigned

前端 未结 4 1240
旧巷少年郎
旧巷少年郎 2020-12-29 22:33

If I need to assign a click function dynamically, is there a way to ensure the click function is only assigned once and not duplicated?

this.click(function()         


        
4条回答
  •  失恋的感觉
    2020-12-29 22:44

    You can unbind the click event before you bind it again, that way you will only have one event attached to it:

    //assuming this is a jquery object.
    this.unbind("click");
    this.click(function(){
      alert("clicked once");
    });
    

    As of jQuery 1.7, click now uses .on (http://api.jquery.com/click/) so the correct code is now

    //assuming this is a jquery object.
    this.off("click");
    this.click(function(){
      alert("clicked once");
    });
    

    This will unbind all click events (including ones created by any plugins you might be using). To make sure you only unbind your event use namespaces. (http://api.jquery.com/off/)

    //assuming this is a jquery object.
    this.off("click.myApp");
    this.on("click.myApp", function(){
      alert("clicked once");
    });
    

    Here myApp is the namespace.

提交回复
热议问题