簡體   English   中英

使用 Jquery .html() 函數替換一個<div>與<script> included?

[英]How do I remove functions from memory in Javascript after using Jquery .html() function to replace a <div> with a <script> included?

以下是我遇到的問題的示例。 我在 ajax 調用后使用 $(locator).html(data) 替換 DIV。 問題是 DIV 內部也有一個 SCRIPT 標簽,並且在我 .empty() 那個 DIV 之后,該 SCRIPT 標簽中的那些函數仍保留在內存中。

有沒有辦法自動/以編程方式刪除/取消注冊/取消定義 SCRIPT 標簽中的所有功能? 我想我認為 Jquery .empty() 會這樣做,但我想不會。 我想我可以做一些像test1 = undefined這樣的手動操作,但我不想對所有的函數都明確地這樣做。

謝謝。

編輯:我正在開發一個遺留產品,所以有幾十個 html 文件可以為 newString 變量加載幾十個函數。 所以我的目標不是改變其中任何一個,而是在替換 div 內容時解決 .empty() 和 .html() 時的這個延遲函數問題。

編輯 2:我不能只是“刪除”函數,因為我並不總是知道函數是什么。 我需要以編程方式執行此操作。 (似乎我一直被標記為重復問題,但同樣,我無法刪除我還不知道的內容)

 function change () { // this newString is mock html data coming back from an ajax call let newString = "<p>Reloaded page</p>"; console.log("#emptyme HTML before empty():") console.log($("#emptyme").html()); $("#emptyme").empty(); console.log("#emptyme HTML AFTER empty():") console.log($("#emptyme").html()); $("#emptyme").html(newString); if (typeof test1 !== "undefined") { $("#error").html("test1() WAS STILL FOUND!!"); console.log("test1() WAS STILL FOUND!! Function definition from memory is:"); console.log(test1); } console.log("finished change function."); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id="emptyme"> <p> Initial page </p> <script> function test1 () { console.log("this is test1 function."); } </script> </div> <button onclick="change()"> load change </button> <div id="error"> </div> </body> </html>

JavaScrip 有一個內部垃圾收集器,您的代碼不必像在 C++ 中那樣銷毀東西

但是,在某些時候,我們希望“銷毀一個函數”,因為它是資源昂貴的因為 js 從上到下運行,如果您稍后在程序中的變量中調用它以釋放這些資源,您可以覆蓋該函數。 甚至在程序的邏輯中稍后再做

   var ExpensiveFunction =( function () {
 //..code
function getRidOfthis1(){ console.log("foo1"); }
function getRidOfthis2(){ console.log("foo2"); }
function getRidOfthis3(){ console.log("foo3"); }
function getRidOfthis4(){ console.log("foo4"); }

//initiate an internal reference to them 
ExpensiveFunction.getRidOfthis1 = getRidOfthis1;
ExpensiveFunction.getRidOfthis2 = getRidOfthis2;
ExpensiveFunction.getRidOfthis3 = getRidOfthis3;
ExpensiveFunction.getRidOfthis4 = getRidOfthis4;

}  );

//Functions available outside of the nesting 
ExpensiveFunction()
ExpensiveFunction.getRidOfthis1();
ExpensiveFunction.getRidOfthis2();

// overidding it 
ExpensiveFunction =0

暫無
暫無

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

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