2017-08-25 18 views
0

我有兩個HTML文件,index.htmlabout.html。 我想打開我的about.htmlindex.html沒有離開我的index.html打開其他URL使用散列#徑自URL

如果我看到,大多數網站使用#about,這樣他們就可以在他們的index.html在他們index更換也許一些div來about.html加載about.html

+0

https://開頭developer.mozilla.org/en-US/docs/Web/API/History_API – epascarello

+0

Google for AJAX將頁面加載到索引頁面中,並以epascarello建議的形式查看History API。 PushState,popState等... –

+0

有關'單頁應用程序路由「的快速Google搜索應該提供足夠的資源來開始使用。 –

回答

0

林不知道這是你想要做什麼,但如果你想在索引頁某處顯示about.html頁有東西在HTML稱爲IFRAME: https://www.w3schools.com/html/html_iframe.asp

但是,如果你想要更多的東西動態你應該看看AJAX和類似的東西,如評論中所建議的。

0

您可以通過使用純javascript的簡單Ajax請求來完成此操作。我寫了一個函數,它得到一個URL的哈希像#about和負載about.html然後把整個內容放到索引頁.container元素:

// Container of external page contents 
var container = document.querySelector('.container'); 

var loadWebpage = function (which) { 
    which = which.slice(1); 
    if (!which) return container.innerHTML = ''; 
    var xhr = new XMLHttpRequest(); 
    xhr.open('GET', which + '.html'); 
    xhr.onload = function() { 
     if (xhr.status === 200) container.innerHTML = xhr.responseText; 
     else console.log(which + ' page not found!') 
    }; 
    xhr.send() 
}; 

window.onhashchange = function() { 
    loadWebpage(location.hash) // When hash changes load that page 
}; 

loadWebpage(location.hash); // When page opens load current hash page 

我希望這可以幫助,祝你好運