## 使用js完成页面跳转

1.window.location.href

<button onclick="window.location.href='https://www.baidu.com'">点击跳转</button>
<button class="click_btn">点击跳转</button>
<script>
    var myBtn=document.getElementsByClassName('click_btn')[0];
    myBtn.onclick=function(){
        window.location.href="https://www.baidu.com";
    }
</script>

2.location.replace

<button onclick="location.replace('https://www.baidu.com')">点击跳转</button>
<button class="click_btn">点击跳转</button>
<script>
    var myBtn=document.getElementsByClassName('click_btn')[0];
    myBtn.onclick=function(){
        window.location.replace("https://www.baidu.com")
    }
</script>

window.location.href 和 location.replace的区别:

  • 有3个页面 a、b、c,如果当前页面是c页面,并且c页面是这样跳转过来的:a->b->c
  • b->c 是通过 window.location.replace("…xx/c")
    此时b页面的url会被c页面代替,并且点击后退按钮时会回退到a页面(最开始的页面)
  • b->c是通过 window.location.href("…xx/c")
    此时b页面的路径会被c页面代替,但是点击回按钮后页面回退的是b页面

3.window.navigate

<button onclick="window.navigate('https://www.baidu.com')">点击跳转</button>
<button class="click_btn">点击跳转</button>
<script>
    var myBtn=document.getElementsByClassName('click_btn')[0];
        myBtn.onclick=function(){
        window.navigate("https://www.baidu.com")
    }
</script>
 

window.location.href 和 window.navigate的区别:
window.navigate 这个方法是只针对IE的,不适用于火狐等其他浏览器。
window.location.href 兼容所有浏览器的。

4.window.open

<button onclick="window.open('https://www.baidu.com')">点击跳转</button>
<button class="click_btn">点击跳转</button>
<script>
    var myBtn=document.getElementsByClassName('click_btn')[0];
        myBtn.onclick=function(){
        window.open("https://www.baidu.com")
    }
</script>

5.self.location 和 top.location

<button onclick="top.location.href='https://www.baidu.com'">点击跳转</button>
<button class="click_btn">点击跳转</button>
<script>
    var myBtn=document.getElementsByClassName('click_btn')[0];
        myBtn.onclick=function(){
            self.location="https://www.baidu.com";
    }
</script>

self.location 和 top.location 的区别和作用:
两者可以结合起来,防止网页被非法引用,假如你的网页地址是:http://www.a.com,别人的网址是http://www.b.com。他在他的页面用iframe等框架引用你的http://www.a.com,那么你可以用一下代码,跳转到你的页面

if(top.location.href!=self.location.href){
  location.href="http://www.a.com";
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值