我有一个使用 jQuery 使用 .load() 刷新的 div。一旦刷新,新内容就会出现在 div 中。但是,新内容中包含 jQuery,它无法正常工作,即使当该内容加载到它自己的页面上时它确实有效。
div 也在父窗口上,但是刷新 div 的 jQuery 代码在 iframe 中。代码调用 top.document(父窗口)刷新 iframe 之外的 div。
我会在这里展示完整的代码:
这是名为 test.php 的主页。它只有一个简单的 iframe,下面是 div,当代码告诉它在 iframe 中刷新时会刷新。
<html>
<head>
</head>
<body >
<iframe src="test2.php" width="400" height="400" frameborder="3"></iframe>
<div id="target">This text will be replaced.</div>
</body>
</html>
这里是 iframe 内的 test2.php,它只是开始 iframe 页面,因此您可以方便地按下一个链接,该链接将激活下一页,该页面在页面加载时打开 jQuery 代码。
<html>
<head>
</head>
<body>
<a href="test3.php">Click Me, if the div below reloads with the jqery content it worked!</a>
</body>
</html>
这是页面 test3.php,其中包含刷新 iframe 外的 div 的 jQuery 代码。 .load() 有效,但 .get() 无效。我尝试使用 .get() 和 .getscript() 调用 jQuery,但这确实有效。我还尝试将它们包装在 .bind() .on() .live() 中,但是如果您知道以您认为可行的方式使用它们的方法,请随时发布。
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$('#target', top.document).load("test4.php");
$('#target', top.document).get('testb.js');
</script>
</head>
<body>
Sent
</body>
</html>
这是test4.php,是刷新后加载到div中的新内容。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<p>....Polo</p>
<script type="text/javascript" src="testb.js"></script>
现在这是我尝试在 div 中实现的 jQuery,它位于页面 test3.php 和 test4.php 上的 testb.js 中。我打算编写更复杂的代码,但由于根本没有 jQuery 起作用,我决定简化它,直到找到 jQuery 不起作用的原因。
var myvariable = "Marco";
$("p").prepend(myvariable);
非常感谢您提供的任何帮助!
最佳答案
我实际上建议您不要这样做。当然,您不应该让片段加载更多片段。这种方式会导致疯狂。
我能够让它发挥作用,但如果让我重新写一遍,我会做不同的事情。它看起来很脆弱,而且很难测试。我相信如果宿主文档中包含所有逻辑并且片段不带任何逻辑,效果会更好。
我在使用 load() 时遇到了问题,但我记不起确切的细节。可能是浏览器之间的差异?我们最终使用 get() 而不是 load()。
最大的症结在于 $('#target') 失败,因为新的 Javascript 没有及时附加到文档。因此,在 load() 调用期间触发时,它不会在主机文档中找到 ID。我能够使用 setTimeout() 解决这个问题
<body>
<div id="stuff>
<script type="text/javascript">
setTimeout(function() {
$('#target', top.document).get('testb.js');
}, 1);
</script>
Sent
</div>
</body>
棘手的一点实际上可能是我获取 DIV 的方式:
$.get("/foo/bar", function(html) {
var div = $('<div></div>');
div.html(html);
div.find('#stuff').detach().appendTo(target);
});
关于jquery - 在一个 div 中实现 jQuery,该 div 的内容刚刚用 jQuery 的 .load() 加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8533036/