jquery prevent duplicate function assigned

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

    assuming that elements are being added to the html and you want to add an event only for elements added:

    function addEvents2Elements()//prevent Duplicate
    {
        //this will add the event to all elements of class="ele2addevent"
        $('.ele2addevent').not('.clickbind').on('click',function(){alert('once');})
    
        //this will add a class an then the class="ele2addevent clickbind"
        $('.ele2addevent').not('.clickbind').addClass('.clickbind');
        //all elements of class="... clickbind" will not be catched anymore in the first line because of .not() every time you call this function
    }
    addEvents2Elements();
    

    be shure that you add only with the class="ele2addevent", because after the bind it will be class="ele2addevent clickbind" and not catched again...

提交回复
热议问题