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>


示例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>


示例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>

注意:所有方法的输出都相同,但location.replace()方法从文档历史记录中删除当前文档的URL。因此,如果希望选项导航回原始文档,最好使用location.assign()方法。


浏览器支持

上述方法的浏览器支持列表:

● Google Chrome

● Apple Safari

● Firefox

● Opera

● Edge



本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_7990