用 JavaScript 重定向到一个网页
JavaScript 中有多种方法可以重新路由用户。这取决于业务要求,该站点应具有哪种重定向行为。你可以通过以下方式重定向用户:
将 location
接口与 Document
和 Window
对象一起使用进行重定向。通常,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.href
和 window.location.assign()
,以编程方式将用户发送到新的 URL。
相关文章
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 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。