jQuery's include方法不'不起作用

jQuery's include method doesn't work

本文关键字:不起作用 方法 jQuery include      更新时间:2023-09-26

由于我的网站只有一个页面,index.html变得非常长,无法阅读。因此,我决定将每个部分放在不同的HTML文件中,并使用jQuery将其包含在内

我使用了jQuery的include,正如这里提到的那样,它包含了一个外部HTML文件,但显然它不适用于我的网站。我真的不知道问题出在哪里。

这是我工作区的链接。

以下是我在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>

我还使用了这种方法来确保文件是可访问的,并且一切都很好。所以问题不在于文件的可访问性

您正在覆盖#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是如何解决页面太长/无法阅读的问题的。

有几件事我觉得很奇怪:

  1. 所有的加载函数都是在文档就绪的情况下运行的,这在具有相同目标的情况下很奇怪。load用正在加载的内容替换(而不是添加)所选元素的内容,您可能正在尝试添加所有html内容,但您当前的设置实际上只是将page7.html加载到#includedContent

  2. 这些路径在我看来很奇怪,我想./可能会导致错误,尽量忽略./

  3. 与其加载整个html页面,您可能只想加载该文件的一部分(我不知道pageX.html看起来如何),例如,您不想完全加载<html>节点,而是只加载内容:.load('page1.html #content')

  4. 您是否正确地包含jquery?您的包含中没有.js