簡體   English   中英

包含javascript文件后,如何刪除/刪除

[英]After include javascript file, how i can delete/remove

因為我使用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次:在控制台ooutput我得到這個。

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;
}

問題不在於功能,問題在於事件綁定。 每次加載文件時,它都會:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM