解释一下 ES6 中的页面重定向?

WBOY
WBOY 转载
2023-09-13 16:33:03 178浏览

解释一下 ES6 中的页面重定向?

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

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

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

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

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

语法

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

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

在上面的语法中,如果我们为 window.location 对象分配一个新的 URL 值,默认情况下,会更改 location 对象的 href 属性的值。

示例

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

在redirect()函数中,我们正在更改位置对象的href属性的值,这会将访问者带到新的URL。

<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.assign()方法在浏览器窗口中加载新文档,在浏览器中重新加载新文档意味着重定向。

语法

按照下面的语法使用 allocate() 方法进行重定向。

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

在上面的语法中,我们将位置对象作为引用来调用 allocate() 方法。

参数

  • New_URL - 这是我们要重定向用户的 URL。

示例

在此示例中,我们使用位置对象的 allocate() 方法在当前浏览器窗口中加载另一个网页。

<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://www.tutorialspoint.com ");
      }
   </script>
</body>
</html>

使用location.replace()方法

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

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

语法

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

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

参数

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

示例

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

<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://www.tutorialspoint.com");
      }
   </script>
</body>
</html>

此外,用户还可以使用窗口对象的navigate()方法进行重定向。 navigate() 方法已被弃用,因此不建议用于重定向。

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

以上就是解释一下 ES6 中的页面重定向?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除