[英]How to bind event listener if not previously set before with jQuery?
在我的代码中的某处执行此命令:
function hook(el) {
console.log("hooked")
}
$('a[href!="#"]').click(hook)
我想防止意外重置挂钩,因为如果我再次执行:
$('a[href!="#"]').click(hook)
糟糕,我会hooked
。 有没有办法查看hook
是否已经与onclick
事件关联?
其背后的内容如下:
function hook(e) {
let uri = e.currentTarget.pathname
e.preventDefault();
if (uri == window.location.pathname)
return;
$.get(uri, function (data) {
data = $(data)
let main = data.find('#main').html()
if (!main) {
window.location.href = uri
return
}
$('#main').html(main)
install() // Reinstall the hook for the new code
if (history.pushState) {
history.pushState({'main': main }, null, uri);
}
}).fail(function () {
window.location.href = uri
});
return false;
}
function install() {
$('a[href!="#"]').click(hook);
}
当然,在这种情况下,我将通过仅重新安装新代码的钩子installOn($('#main'))
如installOn($('#main'))
来解决此问题。
function hook(e) {
let uri = e.currentTarget.pathname
e.preventDefault();
if (uri == window.location.pathname)
return;
$.get(uri, function (data) {
data = $(data)
let main = data.find('#main').html()
if (!main) {
window.location.href = uri
return
}
$('#main').html(main)
// pass in the main context so it only binds on those
install('#main') // Reinstall the hook for the new code
if (history.pushState) {
history.pushState({'main': main }, null, uri);
}
}).fail(function () {
window.location.href = uri
});
return false;
}
function install(parentSelector) {
// find the elements in the context, or the document
$('a[href!="#"]', parentSelector || document).click(hook);
}
//this will bind on all the links that match any where in the document
install();
通过搜索所需的上下文,使用此解决方案可以避免重复的绑定。
由于未传入任何上下文,因此install()
将以所有匹配的元素为目标,因此install方法默认为在文档中查找所有元素。
在ajax中, $('#main').html(main)
用新元素替换$('#main').html(main)
的内容。 确保这些元素在它们上没有任何绑定,因为main
是一个字符串,因此这些元素是全新创建的。
然后, install('#main')
仅针对main内部未绑定的元素,并在其上放置绑定。
因此避免了重复的绑定。
jQuery允许使用事件名称空间。
$('a[href!="#"]').on("click.hook", hook)
然后,当您想重新创建并添加事件时,只需手动进行:
$('a[href!="#"]').off("click.hook");
$('a[href!="#"]').on("click.hook", hook);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.