我想创建一个页面来刷新 div 异步中的内容,同时为用户提供一个 anchor 以允许直接访问 div 中的内容。 (例如 www.website.co.uk/#page1)
我已经设法让内容可以更新 1 页,但是,如果我添加多个页面,它就会停止工作
另外 - 如果我要导航到 URL website.co.uk/#page1,它不会显示 #page1。
有人能帮忙吗?
这是我当前的代码:
HTML :
<h5> <a href="#page1">Test</a></h5>
<h5> <a href="#page2">Test2</a></h5>
JS :
<script type="text/javascript">
var routes = {
'#page1' : '{{site.url}}/page1'
'#page2' : '{{site.url}}/page2'
};
var routeHandler = function( event ) {
var hash = window.location.hash,
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("div1").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", routes[hash], true);
xhttp.send();
};
window.addEventListener('hashchange', routeHandler);
window.addEventListener('load', function() {
var hash = window.location.hash;
if (routes.hasOwnProperty(hash)) routehandler();
});
</script>
最佳答案
你犯了一些小的 js 错误。 所以这是你的固定代码
html:
<h5> <a href="#page1">Test</a></h5>
<h5> <a href="#page2">Test2</a></h5>
<div id="div1"></div>
javascript:
//change these routs
var routes = {
'#page1': '/page1.html',
'#page2': '/page2.html'
};
var routeHandler = function() {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("div1").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", routes[window.location.hash], true);
xhttp.send();
};
window.addEventListener('hashchange', routeHandler);
window.addEventListener('load', function() {
var hash = window.location.hash;
if (routes.hasOwnProperty(window.location.hash)) routeHandler();
});
关于javascript - 使用 AJAX 更改 div 内容 - 如何将导航显示为散列/ anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38146326/