JQuery .get不执行Javascript

时间:2011-11-24 16:54:42

标签: jquery javascript jquery-get

我正在使用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);
});

这是Page 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的文本字段。

2 个答案:

答案 0 :(得分:6)

除非您对其运行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()。更好的方法是在页面内容发生变化时使用事件,但现在这已经足够了。

答案 1 :(得分:5)

您可以使用.load()功能代替.get()。它会自动执行响应中包含的脚本。

以下是文档:.load()