簡體   English   中英

JQuery .get不執行Javascript

[英]JQuery .get doesnt execute Javascript

我正在使用JQuery .get方法從網頁中檢索一些內容(第1頁)並在主頁面的div中顯示它。 問題是檢索到的內容包含一些javascript調用。 正在顯示內容,但Javascript方法未執行 所有頁面都引用了.js文件,因此主要文件中js的可用性不是問題。

這是主頁面中的代碼。 頁面1的URL被賦予.get函數:

$.get(url, function(response) {          
    var newContent = $(response).find("#right");      //Find the content section of the response
    var contentWrapper = $("#wrap");         //Find the content-wrapper where we are supposed to change the content.
    var oldContent = contentWrapper.find("#right");   //Find the old content which we should replace.

    oldContent.replaceWith(newContent);
});

這是第1頁#right(div)中的代碼

Some html tags...    
<p><script type="text/javascript">abc7();</script></p>
<p><script>s(30)</script></p>
Some html tags...

函數abc7和s在.js(普通javascript文件)中可用,該文件在所有頁面的部分中被引用

s(30)應顯示大小為30的文本字段。

除非您對其運行eval() ,否則不會執行內聯JavaScript。 你可以在這里閱讀更多相關信息:

eval()解決方案可能看起來像這樣, 但我認為這是不好的做法

$.get(url, function(response) {          
    var newContent = $(response).find("#right");      //Find the content section of the response
    var contentWrapper = $("#wrap");         //Find the content-wrapper where we are supposed to change the content.
    var oldContent = contentWrapper.find("#right");   //Find the old content which we should replace.

    oldContent.replaceWith(newContent);


    //Find all inline script tags in the new content and loop through them
    newContent.find("script").each(function() {
        var scriptContent = $(this).html(); //Grab the content of this tag
        eval(scriptContent); //Execute the content
    });
});

更好的解決方案是在#right標記上設置標識符/名稱,並執行該特定內容所需的代碼。

就像是:

<div id="right" data-page-name="index">
    <!-- Content -->
</div>

<div id="right" data-page-name="about-us">
    <!-- Content -->
</div>

一個簡單的解決方案,只是將頁面名稱傳遞給將根據頁面執行代碼的函數,看起來像這樣:

$.get(url, function(response) {          
    var newContent = $(response).find("#right");      //Find the content section of the response
    var contentWrapper = $("#wrap");         //Find the content-wrapper where we are supposed to change the content.
    var oldContent = contentWrapper.find("#right");   //Find the old content which we should replace.

    oldContent.replaceWith(newContent);

    var pageName = newContent.attr("data-page-name");

    pageSpecificActions(pageName);
});

function pageSpecificActions(pageName) {
    if (pageName == "index") {
        //Run the code for index page
    } else if (pageName == "about-us") {
        //Run the code for about us page.
    }   
};

這使得JavaScript代碼不會內聯,也不會使用eval() 更好的方法是在頁面內容發生變化時使用事件,但現在這已經足夠了。

您可以使用.load()函數代替.get() 它會自動執行響應中包含的腳本。

這是文檔: .load()

暫無
暫無

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

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