以下是我遇到的問題的示例。 我在 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>