1.window.location.href
// 將js直接寫在html中
<button onclick="window.location.href='https://www.baidu.com'">點擊跳轉</button>
//將js和html分開
<button class="click_btn">點擊跳轉</button>
<script>
var myBtn=document.getElementsByClassName('click_btn')[0]; myBtn.onclick=function(){ window.location.href="https://www.baidu.com"; } </script>
//需要注意的是,這里的window可以省略,即直接使用location.href
<button onclick="location.href='https://www.baidu.com'">點擊跳轉</button>
2.location.replace
// 將js直接寫在html中
<button onclick="location.replace('https://www.baidu.com')">點擊跳轉</button>
//將js和html分開
<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("https://www.baidu")
// 將js直接寫在html中
<button onclick="window.navigate('https://www.baidu.com')">點擊跳轉</button>
//將js和html分開
<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 與 window.location.href 都是實現頁面鏈接跳轉的。
- window.navigate 這個方法是只針對IE的,不適用於火狐等其他瀏覽器,在HTML DOM Window Object中,根本沒有列出window.navigate這個方法,所以這個方法盡量少用,遺忘最好。
- window.location.href 兼容所有瀏覽器的。因此在實現頁面跳轉的時候還是使用這個比較靠譜。
4.window.open("https://www.baidu.com")
// 將js直接寫在html中
<button onclick="window.open('https://www.baidu.com')">點擊跳轉</button>
//將js和html分開
<button class="click_btn">點擊跳轉</button>
<script>
var myBtn=document.getElementsByClassName('click_btn')[0]; myBtn.onclick=function(){ window.open("https://www.baidu.com") } </script>
2.self.location 和 top.location(兩者的寫法實相同的)
// 將js直接寫在html中
<button onclick="top.location.href='https://www.baidu.com'">點擊跳轉</button>
//將js和html分開
<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
3.那么你可以用一下代碼,來轉向你的頁面
if(top.location.href!=self.location.href){ location.href="http://www.a.com"; }
其實使用js實現頁面挑戰的方式還有很多,這里就不一一進行總結,在實際項目中,推薦大家使用第一種方式進行跳轉。