2014-11-05 101 views
1

由於我的網站只有一個頁面,而且index.html變得非常長且無法閱讀。所以我決定把每個部分放在不同的HTML文件中,並使用jQuery來包含它。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方法,以確保文件訪問,一切都很好。所以,問題不在於文件的可訪問性

+0

您是否通過刪除緩存來刷新瀏覽器? – Chakra 2014-11-05 08:19:47

+0

是的。仍然無法正常工作。 – 2014-11-05 08:21:16

+0

刪除'。/'並再次嘗試。 – 2014-11-05 08:23:57

回答

2

您將要覆蓋的#includedContent七次(見jQuery.load文檔)中的內容沒有.js。使用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解決了頁面太長/不可能讀取的問題。

+0

你真棒!非常感謝。 – Apha 2014-11-05 08:41:06

1

有幾件事情,看起來很奇怪對我說:

  1. 所有的負載功能,在文件準備好,同時具有所有的相同的目標是怪異運行。 load取代(不加)與裝載什麼,你可能嘗試添加所有的HTML內容,但當前設置實際上只加載page7.html#includedContent

  2. 的路徑看所選元素的含量對我來說很陌生,我猜./可能會導致錯誤,試圖在任何地方丟掉./。你可能只想加載一段文件(我不知道pageX.html看起來如何),例如你不想完全加載<html>節點,而是僅僅加載內容,而不僅僅是加載整個HTML頁面:.load('page1.html #content')

  3. 你是否正確地包括jquery?有在收錄