JAVASCRIPT實現的WEB頁面跳轉以及頁面間傳值方法
2024-05-06 14:10:06
供稿:網友
但有時候,需要當某事件觸發時,我們先做一些操作,然后再跳轉,這時,就要用JAVASCRIPT來實現這一跳轉功能。
下面是具體的做法:
一:跳轉到新頁面,并且是在新窗口中打開時:
代碼如下:
function gogogo()
{
//do someghing here...
window.open("test2.html");
}
window是一個javascript對象,可以用它的open方法,需要注意的是,如果這個頁面不是一相相對路徑,那么要加http://,比如:
代碼如下:
function gogogo()
{
window.open( "http://www.google.com");
}
二:就在本頁面窗口中跳轉:
代碼如下:
function totest2()
{
window.location.assign( "test2.html");
}
如果直接使用location.assgin()也可以,但是window.location.assign()好像更合理一些,當前窗口的location對象的assign()方法。
另外,location對象還有一個方法replace()也可以做頁面跳轉,它跟assign()方法的區別在于:
replace() 方法不會在 History 對象中生成一個新的紀錄。當使用該方法時,新的 URL 將覆蓋 History 對象中的當前紀錄。
下面學習如何在頁面跳轉的時候進行值的傳遞,當使用window.open()打開新頁面時,瀏覽器會認為這兩個窗口之間有一種打開與被打開的關系,所以在被打開的新窗口中在當前窗口的window對象中有一個window.opener 屬性,這個值里面放著打開窗口的引用,所以可以獲得這個值,進而引用上一頁面內的對象的值,示例如下:
代碼如下:
<html>
<head>
<title>test1</title>
<script type="text/javascript">
function totest2()
{
window.open("test2.html");
}
</script>
</head>
<body>
<label id="label1" >page test1</label>
<br><br>
<input type="text" id="tx1">
<input type="button" id="bt2" value="to test2" onclick="totest2()">
</body>
</html>
代碼如下:
<html>
<head>
<title>test2</title>
<script type="text/javascript">
function getvalue()
{
var pare=window.opener;
if(pare!=null)
{
var what=pare.document.getElementById("tx1");
if(what!=null)
{
alert(what.value);
}
}
}
</script>
</head>
<body>
<label id="label1" >page test2</label>
<br><br>
<input type="button" onclick="getvalue()" value="get test1 page value">
</body>
</html>
這兩個頁面,可以從后一個頁面中獲得前一個頁面中的值,但是我感覺好像不大實用。。。。。。
優點:取值方便.只要window.opener指向父窗口,就可以訪問所有對象.
不僅可以訪問值,還可以訪問父窗口的方法.值長度無限制.
缺點:兩窗口要存在著關系.就是利用window.open打開的窗口.不能跨域.