const routes = {
page1: "pages/page1.html",
page2: "pages/page2.html",
page3: "pages/page3.html",
page4: "pages/page4.html",
page5: "pages/page5.html",
page6: "pages/page6.html",
page7: "pages/page7.html",
page8: "pages/page8.html",
};
let currentPage = null;
let loadingPage = false;
const pageHandlers = {
page1: {
init: () => window.initPage1?.(),
exit: () => window.exitPage1?.()
},
page2: {
init: () => window.initPage2?.(),
exit: () => window.exitPage2?.()
},
page3: {
init: () => window.initPage3?.(),
exit: () => window.exitPage3?.()
},
page4: {
init: () => window.initPage4?.(),
exit: () => window.exitPage4?.()
},
page5: {
init: () => window.initPage5?.(),
exit: () => window.exitPage5?.()
},
page6: {
init: () => window.initPage6?.(),
exit: () => window.exitPage6?.()
},
page7: {
init: () => window.initPage7?.(),
exit: () => window.exitPage7?.()
},
page8: {
init: () => window.initPage8?.(),
exit: () => window.exitPage8?.()
},
};
function clearOldScripts() {
document.querySelectorAll("script[data-dynamic='1']")
.forEach(s => s.remove());
}
function runScripts(container) {
const scripts = container.querySelectorAll("script");
scripts.forEach(oldScript => {
const s = document.createElement("script");
s.dataset.dynamic = "1";
if (oldScript.src) {
s.src = oldScript.src;
} else {
s.textContent = oldScript.textContent;
}
document.body.appendChild(s);
});
}
async function loadPage(name) {
const view = document.getElementById("view");
const url = routes[name];
if (!url) {
view.innerHTML = "无法找到页面";
return;
}
if (loadingPage) {
return;
}
if (currentPage === name) {
return;
}
try {
loadingPage = true;
if (currentPage && pageHandlers[currentPage]?.exit) {
console.log("exit:", currentPage);
pageHandlers[currentPage].exit();
}
clearOldScripts();
const res = await fetch(url, {
credentials: "include"
});
const html = await res.text();
if (html.includes("login.html") || html.includes("登录")) {
window.location.href = "/";
return;
}
view.innerHTML = html;
runScripts(view);
currentPage = name;
if (pageHandlers[name]?.init) {
console.log("init:", name);
pageHandlers[name].init();
}
} catch (e) {
console.error("loadPage error:", e);
view.innerHTML = "页面加载失败";
} finally {
loadingPage = false;
}
}
function setText(id, value, page)
{
if (page && currentPage !== page) {
return;
}
const el = document.getElementById(id);
if (el) el.textContent = value ?? "--";
}
function setBtnStatus(id, enabled, page)
{
if (page && currentPage !== page) {
return;
}
const btn = document.getElementById(id);
if (btn) btn.disabled = !enabled;
}