Ctr*_*roy 2 javascript jquery 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);
});
Run Code Online (Sandbox Code Playgroud)
这是第1页#right(div)中的代码
Some html tags...
<p><script type="text/javascript">abc7();</script></p>
<p><script>s(30)</script></p>
Some html tags...
Run Code Online (Sandbox Code Playgroud)
函数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
});
});
Run Code Online (Sandbox Code Playgroud)
更好的解决方案是在#right标记上设置标识符/名称,并执行该特定内容所需的代码.
就像是:
<div id="right" data-page-name="index">
<!-- Content -->
</div>
<div id="right" data-page-name="about-us">
<!-- Content -->
</div>
Run Code Online (Sandbox Code Playgroud)
一个简单的解决方案,只是将页面名称传递给将根据页面执行代码的函数,看起来像这样:
$.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.
}
};
Run Code Online (Sandbox Code Playgroud)
这使得JavaScript代码不会内联,也不会使用eval().更好的方法是在页面内容发生变化时使用事件,但现在这已经足够了.