【问题标题】:How to open a new tab in spa with vanilla JavaScript?如何使用 vanilla JavaScript 在 spa 中打开一个新选项卡?
【发布时间】:2023-02-02 02:33:22
【问题描述】:

我正在尝试用 html、css 和 vanilla JS 制作一个 SPA(我对 JS 知之甚少)。我遇到的问题是我正在使用的方法可以正常工作,但是当我在新选项卡中打开其中一个部分时,它无法正确寻址网络并给出错误“无法获取”。 有什么办法可以简单地解决这个问题,只用香草 js 吗?

const route = (event) => {
  event = event || window.event;
  event.preventDefault();
  window.history.pushState({}, "", event.target.href);
  handleLocation();
};

const routes = {
  404: "./pages/404.html",
  "/": "./pages/index.html",
  "/vehicles": "./pages/vehicles.html",
  "/services": "./pages/services.html",
  "/contact": "./pages/contact.html",
  "/financing": "./pages/financing.html",
  "/locations": "./pages/locations.html",
};

const handleLocation = async () => {
  const path = window.location.pathname;
  const route = routes[path] || routes[404];
  const html = await fetch(route).then((data) => data.text());
  document.getElementById("main-page").innerHTML = html;
};

window.onpopstate = handleLocation;
window.route = route;

handleLocation();

【问题讨论】:

    标签: javascript single-page-application


    【解决方案1】:

    像这样:

    window.open(location.href);
    

    API 有点不直观。使用其他参数,它可以调用弹出窗口,但默认情况下它会打开一个新的浏览器选项卡。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      相关资源
      最近更新 更多