以下代码仅供演示。
HTML
<div>
<a href='javascript:' id="foo">Foo</a>
</div>
<br>
<div id="target"></div>
JavaScript
jQuery(function () {
jQuery('#foo').bind('click', write);
jQuery('#foo').bind('click', write);
jQuery('#foo').bind('click', write);
jQuery('#foo').bind('click', write);
/*
although I am binding click event four times with same METHOD
I want jQuery to bind it only once and ignore rest request to bind the
same function
*/
});
function write() {
jQuery('#target').append('modified<br>');
}
在 JavaScript 中,我使用 jQuery 将相同的函数绑定(bind)到一个链接四次,但是有什么方法可以让 jQuery 只处理第一个请求并忽略其他请求来绑定(bind)相同的事件。
Demo : using jQuery1.3.2 (我得到了预期的行为,但我希望 jQuery1.7.1 具有这种行为)
最佳答案
您首先应该避免绑定(bind)事件处理程序四次。
如果不能,我建议您先取消绑定(bind)以前的事件处理程序(jQuery 1.7 语法):
jQuery('#foo').off('click', write).on('click', write);
您还可以使用命名空间事件:
jQuery('#foo').off('click.write').on('click.write', write);
任何其他方法都是解决问题的症状,而不是解决问题的原因。 -
<小时/>关于 jQuery 1.3 和 jQuery 1.7 中的不同行为:
As of jQuery 1.4.2 duplicate event handlers can be bound to an element instead of being discarded. This is useful when the event data feature is being used, or when other unique data resides in a closure around the event handler function.
关于jquery - 如何确保一个方法只能绑定(bind)到 jQuery 中的一个元素一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8509629/