英文:
Linking to another html page is not working?
问题
我尝试将侧边栏中显示的设置选项卡链接到一个名为(settings.html)的新HTML页面,但当我点击设置时,它没有将我重定向到(settings.html)页面。
这两个HTML页面都使用相同的外部JavaScript文件,只有在我从HTML代码中删除JavaScript文件时,我才能从侧边栏导航到设置页面。
这是GitHub上的网站代码
[https://github.com/Jehad-Sauafth/Dashboard.git]
英文:
I tried to link the settings tab as shown in the sidebar to a new HTML page called (settings.html), but when I click on the settings it does not direct me to the (settings.html) page.
settings tab on the sidebar
sidebar code
Both HTML pages use the same external JavaScript file, and I only was able to navigate to the settings page from the sidebar, when I removed the JavaScript file from the HTML code.
This is the website code on GitHub
[https://github.com/Jehad-Sauafth/Dashboard.git]
答案1
得分: 0
这是您要翻译的内容:
这是因为您的JavaScript正在阻止所有a元素的默认行为。
将 e.preventDefault()
放入 if 语句中,以便只针对跳转链接阻止默认行为。
const allLinks = document.querySelectorAll("a:link");
allLinks.forEach(function (link) {
link.addEventListener("click", function (e) {
const href = link.getAttribute("href");
// 滚动回顶部
if (href === "#") {
e.preventDefault();
window.scrollTo({
top: 0,
behavior: "smooth",
});
}
// 滚动到其他链接
if (href !== "#" && href.startsWith("#")) {
e.preventDefault();
const sectionEl = document.querySelector(href);
sectionEl.scrollIntoView({ behavior: "smooth" });
}
});
});
英文:
That's because your JavaScript is preventing the default behaviour of all a-elements.
put the e.preventDefault()
into the if-statements, so the default behaviour is only prevented for jump-links.
const allLinks = document.querySelectorAll("a:link");
allLinks.forEach(function (link) {
link.addEventListener("click", function (e) {
const href = link.getAttribute("href");
// Scroll back to top
if (href === "#") {
e.preventDefault();
window.scrollTo({
top: 0,
behavior: "smooth",
});
}
//Scroll to other links
if (href !== "#" && href.startsWith("#")) {
e.preventDefault();
const sectionEl = document.querySelector(href);
sectionEl.scrollIntoView({ behavior: "smooth" });
}
});
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论