迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

用 JavaScript 重定向到一个网页

作者:迹忆客 最近更新:2023/03/10 浏览次数:

JavaScript 中有多种方法可以重新路由用户。这取决于业务要求,该站点应具有哪种重定向行为。你可以通过以下方式重定向用户:

location 接口与 DocumentWindow 对象一起使用进行重定向。通常,window.location.href 返回当前页面的 URL。例如,如果运行以下代码,你将看到页面 URL:

console.log(window.location.href)

输出:

"https://www.jiyik.com/"

诀窍是通过为 window.location.href 分配一个不同的 URL 来替换此 URL。这将使浏览器加载 URL 指定的页面,从而重定向到该页面。就网站历史记录堆栈而言,此方法更改当前参考 URL。以下代码将导航到 DelfStack 的操作方法页面。

window.location.href = "https://www.jiyik.com/w/";

如果你希望永久地移至网页,请使用 location.replace。区别在于,location.replace 将用新的 URL 替换当前的 URL。因此,用户将无法返回到先前的 URL。就浏览器历史记录堆栈而言,该方法会弹出最后一个网页 URL,并将 URL 推送到值中。

window.location.replace("https://www.jiyik.com");

执行此操作将加载 https://www.jiyik.com 网站。

location.replace() 一样,assign() 方法也具有以下区别:当前链接保留在浏览器历史记录中。因此,用户将能够使用浏览器后退按钮返回上一页。此方法还将目标 URL 作为参数。

window.location.assign("https://www.jiyik.com");

在较旧的浏览器中,尤其是版本 8 或更低版本的 Internet Explorer,不支持位置界面。因此,我们动态创建锚标签(<a>),并使用目标 URL 设置 href 属性。如前所述,锚标签是一个被动元素,需要用户交互才能调用它。因此,在代码中触发了 click 事件,以使重定向生效。

let targetURL = 'https://www.jiyik.com';
let newURL = document.createElement('a');
newURL.href = targetURL;
document.body.appendChild(newURL);
newURL.click();

在这里,我们通过以下方式实现重定向:

浏览器将加载新的 URL。

根据业务需求,最好在用户进入维护不足的网站网页时使用 meta 刷新方法来重定向用户。如果导航旨在基于用户单击,则使用锚标签非常普遍。我们可以使用 JavaScript 中 locationwindow.location.hrefwindow.location.assign(),以编程方式将用户发送到新的 URL。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便