因为我的网站只有一页,而且 index.html
变得很长而且无法阅读。所以我决定将每个部分放在不同的 HTML
文件中,并使用 jQuery 来包含它。
我按照提到的方式使用了 jQuery 的包含 here包含外部 HTML
文件,但显然它不适用于我的网站。我真的不知道是什么问题。
Here是我工作区的链接。
这是我在 index.html
文件中所做的,以包含其他部分
<script src="./js/jquery-1.11.1.min"></script>
<script>
$(function() {
$("#includedContent").load("./page1.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page2.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page3.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page4.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page5.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page6.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page7.html");
});
</script>
我还使用了 this确保文件可访问并且一切正常的方法。所以问题不在于文件的可访问性
最佳答案
您正在覆盖 #includedContent
的内容七次(参见 jQuery.load
的文档)。使用 AJAX 时,无法保证哪个请求会先完成,因此您最终会在容器内得到随机的页面内容。
解决方案是为每个页面创建容器并将每个页面加载到其专用容器中,如下所示:
<div id="includedContent">
<div class="page1"></div>
<div class="page2"></div>
<div class="page3"></div>
</div>
$(document).ready(function() {
$("#includedContent .page1").load("page1.html");
$("#includedContent .page2").load("page2.html");
$("#includedContent .page3").load("page3.html");
});
注意:说了这么多,我不明白AJAX是如何解决页面太长/无法阅读的问题。
关于javascript - jQuery 的包含方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26752432/