bind event only once

前端 未结 13 2293
予麋鹿
予麋鹿 2020-12-05 03:45

I have the following code:

function someMethod()
{
  $(obj).click(function {});
}

someMethod is called twice and thus click event is binded

13条回答
  •  情话喂你
    2020-12-05 04:27

    There is no built in method to determine if you have already bound this particular function. You can bind multiple click functions to an object. For example:

    $('#id').bind('click', function(){
    alert('hello');
    });
    
    
    $('#id').bind('click', function(){
    alert('goodbuy');
    });
    

    if you do the above when the object is clicked it will alert hello then goodbye. To make sure only one function is bound to the click event unbind the click event handler then bind the desired function like this:

    $(obj).unbind('click').bind('click', function(){... });
    

提交回复
热议问题