如何使jQuery`bind`或`on`事件处理程序具有幂等性 [英] How to make jQuery `bind` or `on` event handlers idempotent
问题描述
有没有办法可以调用 $(选择器).bind('click',handler)
或 $(selector).on ('click',handler)
多次,这样处理程序只连接一次?
Is there a way that I can call $(selector).bind('click', handler)
or $(selector).on('click', handler)
multiple times such that the handler only gets attached once?
现在,我有多个具有不同成功回调的AJAX处理程序,每个回调都会在页面上重新呈现一组不同的元素。理想情况下,我想将重新连接事件例程重构为单个函数而不是所有例程。
Right now, I have multiple AJAX handlers with different success callbacks, each of which re-renders a different set of elements on the page. Ideally I'd like to refactor the "reattach events" routine to a single function rather than a routine for all.
我能想到的唯一方法就是这样做现在是明确取消绑定,例如:
The only way I can think of to do this right now is to explicitly unbind, for example:
$(selector).off('click');
$(selector).on('click', handler);
寻找一种自动执行此类操作的方法。
Looking for a way to do something like that automatically.
推荐答案
更好的方法是将 .on
调用移动到容器。如果你有一个容器,那么<code> .on 会粘在你的选择器上的任何现有或新的孩子身上:
A better approach is just to move the .on
call to a container. If you have a container, the .on
sticks around and is applied to any existing or new children matching your selector:
$(container-selector).on("click", "element-selector", function(event){
// do stuff
});
干杯。
这篇关于如何使jQuery`bind`或`on`事件处理程序具有幂等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!