簡體   English   中英

jQuery的include方法不起作用

[英]jQuery's include method doesn't work

因為我的網站只有一個頁面,而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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM