解释 ES6 中的页面重定向?


本教程将介绍 JavaScript ES6 版本中引入的页面重定向。页面重定向是一种从当前 URL 将网页访问者发送到另一个 URL 的方法。我们可以将用户重定向到同一网站的不同网页,或其他网站或服务器。

在 JavaScript 中,窗口是一个全局对象,其中包含 location 对象。我们可以使用 location 对象的不同方法进行 ES6 中的页面重定向,这正是我们将在下面学习的内容。

使用 window.location 对象的 href 属性值

窗口全局对象的 location 对象包含 href 属性。location 对象包含有关您当前所在网页位置的所有信息。location 对象的“href”属性包含当前 URL。

要将访问者重定向到不同的 URL,我们需要更改 Web 浏览器中的当前 URL,这可以通过更改 location 对象的 href 属性值来实现。

语法

用户可以按照以下语法通过更改 href 属性的值来将访问者重定向到另一个页面。

window.location = "<new_URL>";
window.location.href = "<new_URL>";

在上述语法中,如果我们将新的 URL 值赋给 window.location 对象,则默认情况下会更改 location 对象的 href 属性的值。

示例

在下面的示例中,我们创建了一个带有文本“重定向到另一个网页”的按钮。当用户单击该按钮时,我们将调用 JavaScript 的 redirect() 函数。

在 redirect() 函数中,我们更改了 location 对象的 href 属性的值,这将访问者带到一个新的 URL。

Open Compiler
<html> <body> <h2>Using window.location.href attribute for page redirection</h2> <p>Click below button to redirect </p> <button id="redirect" onclick="redirect()"> Redirect to the another webpage </button> <script type="text/javascript"> function redirect(){ window.location.href="https://tutorialspoint.com/" } </script> </body> </html>

使用 location.assign() 方法

assign() 是在 location 对象内定义的方法。我们可以使用 location.assign() 方法在浏览器窗口中加载新文档,在浏览器中重新加载新文档意味着重定向。

语法

请按照以下语法使用 assign() 方法进行重定向。

window.location.assign("<new_URL>");

在上述语法中,我们使用 location 对象作为引用来调用 assign() 方法。

参数

  • New_URL − 这是我们想要将用户重定向到的 URL。

示例

在这个例子中,我们使用了 location 对象的 assign() 方法在当前浏览器窗口中加载另一个网页。

Open Compiler
<html> <body> <p>Using the <i>window.location.assign()</i> method to redirect users to another webpage.</p> <button id="redirect" onclick="redirect()">Redirect </button> <script type="text/javascript"> function redirect(){ window.location.assign("https://tutorialspoint.com "); } </script> </body> </html>

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

使用 location.replace() 方法

location 对象的 replace() 方法的工作方式与 assign() 方法相同。replace() 和 assign() 方法之间的唯一区别在于,replace() 方法用历史堆栈中的新 URL 替换当前 URL。因此,它不允许历史堆栈包含有关先前网页的信息,这意味着用户无法返回。

assign() 方法向历史堆栈添加新条目。因此,用户可以使用 Web 浏览器的后退按钮返回上一页。

语法

用户可以按照以下语法使用 replace() 方法进行页面重定向。

Window.location.replace("<redirection_URL>")

参数

  • Redirection_URL − 重定向 URL 是我们要将网页访问者重定向到的新 URL。

示例

在这个例子中,我们使用了 location 对象的 replace() 方法将用户重定向到新的网页。在输出中,用户可以尝试单击后退按钮以在重定向后返回。replace() 方法不允许返回。

Open Compiler
<html> <body> <p>Using the <i>window.location.replace()</i> method to redirect users to another webpage.</p> <button id="redirect" onclick="redirect()">Redirect </button> <script type="text/javascript"> function redirect(){ window.location.replace("https://tutorialspoint.com"); } </script> </body> </html>

此外,用户还可以使用 window 对象的 navigate() 方法进行重定向。navigate() 方法已弃用,因此不推荐用于重定向。

我们学习了 3 到 4 种将用户重定向到不同网页的方法。用户可以根据自己的需求使用任何方法。例如,如果他们想替换当前 URL,请使用 replace() 方法;否则,请使用 assign() 方法。用户可以使用 reload() 方法来获取新的服务器数据。

更新于:2022-12-29

浏览量 181 次

启动您的 职业生涯

通过完成课程获得认证

开始
广告