×

教你JS跳转“三部曲”:location.href、location.replace()和location.assign()

作者:andy0012020.03.12来源:Web前端之家浏览:7287评论:0

大清早学习下东西吧,使用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.jiangweishan.com"; 
         } 
      </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.jiangweishan.com"); 
         } 
      </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.jiangweishan.com"); 
         } 
      </script> 
   </body> 
</html>

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/js8203984092380498.html

网友评论文明上网理性发言 已有0人参与

发表评论: