<body> 使用哈希 # 打开其他 URL 而不保留 URL



我有两个HTML文件,index.htmlabout.html。 我想在index.html里打开我的about.html,而不离开我的index.html

如果我看到,大多数网站都使用#about,因此他们可以在他们的index.html中加载about.html,并替换他们index中的一些div 来about.html

我不确定这是你想要做的,但如果你想在索引页的某处显示关于.html页面,HTML中有一些叫做iframe的东西: https://www.w3schools.com/html/html_iframe.asp

但是,如果你想要更动态的东西,你应该按照评论中的建议研究AJAX和类似的东西。

你可以通过使用简单的Ajax请求和纯javascript来做到这一点。我编写了一个函数,该函数获取像#about这样的 url-hash 并加载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

我希望它有所帮助,祝你好运

相关内容

最新更新