Javascript innerHTML not changing



我正在创建一个简单的面板,我想更改页面的部分。为了改变这一点,我使用了innerHTML。但当我运行它时,UI没有改变,控制台中的值也没有改变。

我想做的是用html文件更改页面的内容,而不是触摸侧边栏。我得到的是,它不会改变它,但当我在URL标记中使用它时,它可以工作,当多次单击后单击它时,有时也可以工作。

Javascript文件。如下

const route = (event)=>{
event = event || window.event;
event.preventDefault();
window.history.pushState({}, "", event.target.href);
routeHandler();
};
const routes = {
404: "/html/404.html",
"/": "/html/home.html",
"/school" : "/html/school.html",
"/student" : "/html/student.html"
};
const routeHandler = async ()=>{
const path = window.location.pathname;
const route = routes[path] || routes[404];
const html = await fetch(route).then((response)=> response.text());
console.log(html);
document.getElementById("main-page").innerHTML = html;
};

我的index.html机身

<div class="sidebar">
...
<li>
<a href="/" onclick="route()">
<i class='bx bx-grid-alt'></i>
<span class="link_name">Dashboard</span>
</a>
<ul class="sub-menu blank">
<li><a href="#" class="link_name">Dashboard</a></li>
</ul>
</li>
...
</div>
...
<section id="main-page"></section>
<script src="/script/router.js"></script>
<script src="/script/index.js"></script>

其他页面如下

<div class="content">
<h1>Course Section</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Sed rem non doloribus voluptatibus perferendis alias ea ratione nulla inventore beatae exercitationem totam velit assumenda enim vitae, fugiat molestias rerum nemo?</p>
</div>

那么,为什么这不起作用呢?

也许您应该尝试使用XMLHttpRequest。了解其工作原理的基本示例

<!DOCTYPE html><html>
<body>
<div id="sidebar">
<button type="button" onclick="loadXMLDoc('A.txt')">Change Content A</button>
<button type="button" onclick="loadXMLDoc('B.txt')">Change Content B</button>
</div>
<div id="main-page">
</div>
<script>
function loadXMLDoc(chosen_option) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("main-page").innerHTML =
this.responseText;
}
};
xhttp.open("GET", chosen_option, true);
xhttp.send();
}
</script>
</body>
</html>

这种方式全部";仪表板";保持不变,但浏览器只获取"的内容;主页";分区

您需要有内容文件(在本例中为A.txt和B.txt(。在内容文件中,您应该为主分区放置内容

考虑使用javascript设置iframe-src,并对其进行适当的样式设置。

最新更新