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";
}