【问题标题】:After include javascript file, how i can delete/remove包含 javascript 文件后,我如何删除/删除
【发布时间】:2019-04-12 03:14:25
【问题描述】:

因为我使用 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;
}

【问题讨论】:

    标签: javascript jquery cross-browser


    【解决方案1】:

    问题不在于函数,问题在于事件绑定。每次加载文件时,它都会:

    $(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 ...);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      • 1970-01-01
      • 2020-02-02
      • 2011-03-21
      • 1970-01-01
      • 2013-03-20
      • 1970-01-01
      相关资源
      最近更新 更多