javascript - jQuery 的包含方法不起作用

标签 javascript jquery html ajax

因为我的网站只有一页,而且 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/

相关文章:

javascript - 如果使用 js 在我的网站上没有图像,如何设置手动默认图像?

javascript - Preg 在 javascript 中替换

jquery - 寻找 jQuery 事件类型的完整列表

javascript - 除非调整窗口大小,否则 iFrame 不会在 Chrome 中加载

html - CSS 疯狂 inline-block 不可移动边距

javascript - 使用 JavaScript 更改事件监听器对产品列表进行排序

javascript - JQuery - Serialize() 一个不是表单但位于表单内部且是表单一部分的对象

javascript - 如何在 JavaScript 中连接变量和字符串?

javascript - 如何取消选中复选框?

jquery - 使用 jQuery 检测何时加载新推文?