我正在尝试使用.load()方法将一个页面加载到另一个页面.这个加载的页面包含一个我想在加载完成后执行的脚本.我已经整理了一个准系统示例来演示:
index.html的:
<html>
<head>
<title>Jquery Test</title>
<script type="text/javascript" src="script/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#nav a').click(function()
{
$('#contentHolder').load('content.html #toLoad', '', function() {});
return false;
});
});
</script>
</head>
<body>
<div id="nav">
<a href="content.html">Click me!</a>
</div>
<hr />
<div id="contentHolder">
Content loaded will go here
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
Content.html:
<div id="toLoad">
This content is from content.html
<div id="contentDiv">
This should fade away.
</div>
<script type="text/javascript">
$('#contentDiv').fadeOut('slow', function() {} );
</script>
</div>
Run Code Online (Sandbox Code Playgroud)
单击链接时,内容应加载,第二段应逐渐消失.但它不会执行.如果我在content.html的脚本中粘贴一个简单的警报(""),它也不会执行.
但是,如果我在.load()调用中取消#toLoad选择器,它可以正常工作.我不知道为什么会这样,因为块显然属于#toLoad div的范围.我不想避免使用选择器,因为实际上content.html将是一个完整的HTML页面,我只想要一个选择部分.
有任何想法吗?如果content.html中的脚本在.load()回调中,它工作正常,但我显然不希望index.html中包含该逻辑.
我可能有回调使用.getScript()来加载"content.html.js"然后在那里有逻辑,这似乎工作?如果可能的话,我宁愿将脚本保留在content.html中,以便在正常加载时它也能正常执行.事实上,无论如何我可能会这样做,但我想知道为什么以上不起作用.
小智 4
如果您查看 jquery 源代码,您将看到 .load() 方法只是从加载的内容中删除所有脚本(如果指定了选择器)。
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
complete: function( res, status ) {
// If successful, inject the HTML into all the matched elements
if ( status === "success" || status === "notmodified" ) {
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div />")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(res.responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
res.responseText );
}
if ( callback ) {
self.each( callback, [res.responseText, status, res] );
}
}
Run Code Online (Sandbox Code Playgroud)