天天看点

如何使用JavaScript重定向到其他网页?

在JavaScript中有好几种方法可以重定向到另一个网页,下面本篇文章就来给大家介绍一些使用JavaScript重定向到另一个网页的方法,希望对大家有所帮助。

如何使用JavaScript重定向到其他网页?

如何使用JavaScript重定向到其他网页?

使用JavaScript重定向到其他网页的一些方法:

  • location.href
  • location.replace()
  • location.assign()

语法:

location.href="URL"
//或者
location.replace("URL")
//或者
location.assign("URL")           

参数:接受单个参数的URL,这是必需的。用于指定新网页的引用。

返回值:无返回值。

示例1:使用location.href属性重定向到其他网页

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head> 
    <body> 
      <p>这是<i>location.href</i>方式的示例</p> 
      <button onclick="myFunc()">点击这里</button> 

      <!--重定向到其他网页的脚本-->   
      <script> 
         function myFunc() { 
           window.location.href="https://www.html.cn"; 
         } 
      </script> 
   </body> 
</html>           

效果图:

如何使用JavaScript重定向到其他网页?

示例2:使用location.replace()方法重定向到其他网页

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head> 
    <body> 
      <p>这是<i>location.replace()</i>方式的示例</p> 
      <button onclick="myFunc()">点击这里</button> 

      <!--重定向到其他网页的脚本-->   
      <script> 
         function myFunc() { 
          location.replace("https://www.html.cn"); 
         } 
      </script> 
   </body> 
</html>           
如何使用JavaScript重定向到其他网页?

示例3:使用location.assign()方法重定向到其他网页

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head> 
    <body> 
      <p>这是<i>location.assign()</i>方式的示例</p> 
      <button onclick="myFunc()">点击这里</button> 

      <!--重定向到其他网页的脚本-->   
      <script> 
         function myFunc() { 
          location.assign("https://www.html.cn"); 
         } 
      </script> 
   </body> 
</html>           
  • Google Chrome
  • Apple Safari
  • Firefox
  • Opera
  • Edge

    原文地址:如何使用JavaScript重定向到其他网页?

继续阅读