bind event only once

前端 未结 13 2294
予麋鹿
予麋鹿 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:24

    You can add css class to the binded elements and then filter them out:

    function someMethod()
    {
        $(obj).not('.click-binded')
              .click(function {})
              .addClass('click-binded');
    }
    

    This method may be used also for plugins:

      $(obj).not('.datetimepicker-applied')
            .datetimepicker()
            .addClass('datetimepicker-applied');
    

提交回复
热议问题