正文
如何從頁面1中向頁面2傳入一張圖檔的路徑呢?
首先來複習下window.location
window.location對象用于獲得目前頁面的位址 (URL),并把浏覽器重定向到新的頁面.
<!--設定或擷取對象指定的檔案名或路徑。
console.log(window.location.pathname)
設定或擷取整個 URL 為字元串。
console.log(window.location.href);
設定或擷取與 URL 關聯的端口号碼。
console.log(window.location.port)
設定或擷取 URL 的協定部分。
console.log(window.location.protocol)
設定或擷取 href 屬性中在井号“#”後面的分段。
console.log(window.location.hash)
設定或擷取 location 或 URL 的 hostname 和 port 号碼。
console.log(window.location.host)
設定或擷取 href 屬性中跟在問号後面的部分。
console.log(window.location.search)-->
是以這兒我們用到window.location.search
1 . 在頁面1,通過點選,跳轉到頁面2,
//$('#aa').click()即為給id名為aa的元素添加點選事件
$('#aa').click(function(){
window.location.href="index3.html/?src=img/apple.jpg";
})
2 . 這樣頁面2的url為下圖所示
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsISN1ETN1ITMwIDNxATM2EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
3 .在頁面2中通過對url進行操作。
//建立變量sear來接受window.location.search的值
var sear=window.location.search;//即為"?src=img/apple.jpg"
console.log(sear)
//判斷是否存在sear
if(sear.indexOf('?')!=-) arr=sear.substr().split('&');//arr=["src=img/apple.jpg"]
new_arr=arr[].split('=');//new_arr=["img/apple.jpg"]
console.log(arr);
}
4.這樣就可以将頁面1中的參數傳到頁面2啦