[英]No page reloading when navigation is clicked, replacing .html contents with another .html
[英]How to show another HTML file's contents on the same page when a link is clicked?
當我在頁面左側有幾個鏈接時,如何在單擊鏈接時在同一頁面上顯示另一個HTML文件的內容?
簡單的解決方案: iframe
,更好但更難的解決方案: AJAX
。
iFrame
要創建iframe,請將其放入您的源代碼中: <iframe src="the/URL/of/a/page.html"></iframe>
。 這將在iframe中的the/URL/of/a/page.html
中顯示文件。 可以使用CSS(僅供參考)設置iframe的樣式。 然后給您所有的<a>
sa類,我為示例JavaScript設置了link
,並為iframe設置了ID(我采用了iframe
)。 (如果沒有JS AFAIK,則無法做到這一點,否則您將不得不使用已廢棄的<frameset>
。)示例JS:
var links = document.getElementsByClassName("link"); // Get all the elements with the class link for (var i; i < links.length; i++) { // Loop over all the links links[i].onclick = function(e) { // Tell them what to do when they're clicked e.preventDefault(); // Prevent the browser from navigating to the address of the links href document.getElementById("iframe").src = links[i].href; // Set the iframe's src to the href of the a. } }
AJAX
這有點困難,使用jQuery之類的庫極大地簡化了此任務。 在我的示例中,我使用jQuery,否則它將花費更多的代碼行。
您需要一個div
來顯示加載的頁面,在頁面上放一個並為其指定ID(在示例中使用了resultbox
)。 請注意,與iframe
解決方案相反,AJAX通常僅適用於同一域中的文件(盡管我相信我在SO上看到了一些解決方法/漏洞)。 這個例子:
$(".link").click(function(e) { // If an element with the class 'link' get's clicked... e.preventDefault(); $("#resultbox").load("the/URL/of/a/page.html"); // ... load the contents of the file at the/URL/of/a/page.html into the element with the ID 'resultbox' });
注意:我沒有測試任何一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.