我正在尝试构建一个菜单,该菜单可动态更改ID为“ main-content”的div的内容。
我已经到了可以运行switch语句的地步,并且根据所单击的链接调用了正确的大小写,但是它并没有使用新内容来更新innerHTML。
let currentUrl;
const content = document.getElementById('main-content');
const logo = document.getElementById('header-logo');
const links = document.getElementsByClassName('side-menu__sub-menu__item-link');
const domain = '$*cdn';
const pagesDir = 'views/styleguide/pages';
const link = `${domain}/${pagesDir}`;
const pages = {
"Typography": {
"title": 'Typography',
"link": `${link}/typography.html`,
},
"ColorPalette": {
"title": 'Color Palette',
"link": `${link}/colorPalette.html`,
},
"Home": {
"title": 'Home',
"link": `${link}/home.html`,
}
}
async function fetchHtmlAsText(url) {
return await (await fetch(url)).text();
}
async function LoadPage(href) {
switch(href) {
case pages.Typography.title:
console.log("page loaded ", href, "type");
content.innerHTML = await fetchHtmlAsText(pages.Typography.link);
break;
case pages.ColorPalette.title:
console.log("page loaded ", href, "color");
content.innerHTML = await fetchHtmlAsText(pages.ColorPalette.link);
break;
default:
content.innerHTML = await fetchHtmlAsText(pages.Home.link);
break;
};
}
for (let link = 0; link < links.length; link += 1) {
links[link].addEventListener('click', () => {
const parent = links[link].parentElement.parentElement;
let href;
// check if parent element exists and if it does get the
// value of the href attribute
if (parent) {
href = parent.getAttribute('href').replace('#', '');
}
// Check if link matches the current page
if (currentUrl !== href) {
LoadPage(href);
}
});
}
logo.addEventListener('click', () => {
LoadPage('');
});
sidemenu.html
<div id="side-menu" class="side-menu">
<div id="hamburger" class="side-menu__hamburger">
<div id="side-menu__hamburger__line-01" class="side-menu__hamburger__line side-menu__hamburger__line__01"></div>
<div id="side-menu__hamburger__line-02" class="side-menu__hamburger__line side-menu__hamburger__line__02"></div>
<div id="side-menu__hamburger__line-03" class="side-menu__hamburger__line side-menu__hamburger__line__03"></div>
</div>
<ul class="side-menu__sub-menu">
<a class="side-menu__sub-menu__item-link" href="#colorPalette">
<li class="side-menu__sub-menu__item">
<span class="side-menu__sub-menu__item__icon-container">
<i class="fas fa-paint-brush side-menu__sub-menu__item__icon-container__icon"></i>
</span>
<span class="side-menu__sub-menu__item__text">
Colour Palettes
</span>
</li>
</a>
<a class="side-menu__sub-menu__item-link" href="#typography">
<li class="side-menu__sub-menu__item">
<span class="side-menu__sub-menu__item__icon-container">
<i class="fas fa-text side-menu__sub-menu__item__icon-container__icon"></i>
</span>
<span class="side-menu__sub-menu__item__text">
Typopgraphy
</span>
</li>
</a>
</ul>
</div>