jquery prevent duplicate function assigned

前端 未结 4 1224
旧巷少年郎
旧巷少年郎 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:53

    I would like to add to Marius's answer--

    In avoiding duplicate bindings you don't want to accidentally unbind something if there is supposed to be more than one function bound to an event. This is especially important when you are working on something with multiple developers. To prevent this you can use event namespacing:

    //assuming this is a jquery object.
    var alertEvent = 'click.alert'
    this.unbind(alertEvent).bind(alertEvent,function(){
      alert('clicked once');
    });
    

    Here 'alert' is the name of the namespace for your click event and only your functions that were bound with that namespace will be unbound.

提交回复
热议问题