链接到另一个HTML页面无法正常工作?

huangapple go评论67阅读模式
英文:

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" });
    }
  });
});

huangapple
  • 本文由 发表于 2023年4月17日 06:53:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76030705.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定