因为我使用ajax来访问我网站上的内容;我有这段代码#1,该代码动态包含一个不同目录的javascript文件(取决于所加载的内容),但是包含相同的功能。
代码1:
var formContent = $("body form").first().attr('name');
if (typeof formContent != 'undefined') {
var uri = "classJS/" + formContent + "/jsc.js"; //File Javascript repeate in diferent directories.
fetch(uri, { method: 'GET', type: 'HEAD' }).then(function(resp) {
if (resp['status'] === 200) {
//if Exist the Default Function (FunctionForms) set this to undefined.
if (window.isFunction(window.FunctionForms)) {
window.FunctionForms = undefined;
}
$.getScript(uri).done(function() {
window.FunctionForms(formEvent); //call or Re-Call the function.
});
} else {
console.log('%cNot find Script file: ' + formEvent, 'color: red');
}
});
}
代码2,此功能(在每个文件中都有)专门用于为加载的内容收取其他特定功能,例如:
代码#2文件1 :(可以加载N次)
function FunctionForms(formEvent) {
console.log('%cCarga de Script JS para: ' + formEvent, 'background: #222; color: #bada55');
window.Test();
}
function Test(){
$('[name="s_list_2"]').unbind('click.form');
$(document).on("click.form", '[name="s_list_2"]', function(event) {
console.log('Is clicked');
});
}
来自其他目录的同一文件的内容可能稍有不同:
function FunctionForms(formEvent) {
//not used.........
console.log('%cCarga de Script JS para: ' + formEvent, 'background: #222; color: #bada55');
}
然后:如果我输入相同的内容5次; 则系统包含了5次相同的文件;但它不会覆盖或删除该函数,相反,它会将其存储在不同的实例中;导致它运行N次:在控制台输出中,我得到了。
VM6933:27 Is clicked
VM6944:27 Is clicked
VM6986:27 Is clicked
VM7022:27 Is clicked
VM7105:27 Is clicked
我知道这显然没有达到我的期望:
if (window.isFunction(window.FunctionForms)) {
window.FunctionForms = undefined;
}
答案 0 :(得分:0)
问题不在于函数,问题在于事件绑定。每次加载文件时,它都会:
$(document).on("click.form", '[name="s_list_2"]', function(event) {
console.log('Is clicked');
});
这将添加另一个点击处理程序。
您似乎先尝试删除了旧的处理程序,但操作不正确。要删除委托的事件处理程序,您必须对.off()
使用相同的委托语法:
$(document).off("click.form", '[name="s_list_2"]');
您正在使用:
$('[name="s_list_2"]').unbind('click.form');
这只会删除添加了以下内容的处理程序:
$('[name="s_list_2"]').on('click.form', function ...);