需求:兩個靜態(tài)頁面,打開新的頁面后需要根據(jù)當前頁面點擊的按鈕去確定新頁面默認的顯示
解決思路
在跳轉后傳遞值坏为,然后新頁面獲取值逗抑,根據(jù)值去添加案例的 class,使對應的案例標題顏色改變
解決方法1—隱藏域
window.open() 父子頁面的傳參&傳值
首先夹攒,父頁面中button 跳轉采用
window.open('case-detail.html');
button綁定 value 值
<button class="btn-arr" value="0">
案例詳情<br />
<i class="icon iconfont icon-iconset0417"></i>
</button>
子頁面中獲取 vlaue的值
var a = window.opener.document.getElementById("btn-case").value;
因為我這邊涉及多個蜘醋,如果使用同一個id 不能獲取vlaue 值,所以我在頁面上寫了一個空的按鈕用來存儲所點擊的 vlaue 值
<button id="btn-case" value=""></button>
當點擊 button 時咏尝, 把當前 button 的 vlaue值賦值為** id="btn-case" ** 的 vlaue值
$('.btn-arr').click(function(){
$('#btn-case').val($(this).val());
window.open('case-detail.html');
});
然后在子頁面中就可以通過去獲取** id="btn-case"** 的** vlaue值压语,來設置跳轉后的默認顯示闲先,選項比較可以采用switch case** 語句
var a = window.opener.document.getElementById("btn-case").value;
a = parseInt(a);
var aA = $('.case-detail .tab-ul').find('a');
switch(a){
case 1:
aA.removeClass('active');
aA.eq(1).addClass('active');
break;
case 2:
aA.removeClass('active');
aA.eq(2).addClass('active');
break;
default:
break;
}
注意:這里的a ** 使用alert(typeof(a));**彈出 String ,使用switch case 語句時需要轉換為 number 值无蜂,或者 **case **值設置為 ‘1’伺糠,添加引號。
網(wǎng)上還有很多兩個靜態(tài)頁面的傳值斥季,選用這個是因為取值方便.只要window.opener指向父窗口,就可以訪問所有對象.不僅可以訪問值,還可以訪問父窗口的方法.值長度無限制. 缺點:兩窗口要存在著關系.就是利用window.open打開的窗口.不能跨域.
解決方法2—Url傳值
url傳值 形如:case.html?id=1&msg=true
跳轉頁面時把參數(shù)寫入Url后的參數(shù)中训桶,這種方法對與a標簽跳轉很方便,后面價格參數(shù)即可酣倾,下面來看看頁面中怎么去應用
頁面A
<div id="Div1"><a href="case.html?id=1">案例詳情</a><div>
對于上面的案例可以直接在html上把參數(shù)帶上舵揭,在打開的頁面中獲取。
如果對于input框輸入躁锡,或者其他需要傳入的值
<input id="test" type="text" value=""/>
<button id="btn">案例詳情<button>
var oInput = document.getElementById("test");
var oBtn = document.getElementById("btn");
oBtn.onclick = function(){
var id = oInput.value;
window.location.href = "case.html?id="+id;
//傳遞多個參數(shù)
window.location.href = "case.html?id="+id+"&msg=123";
};
頁面B
B頁面通過url去分割找到需要的參數(shù)
/*
* 獲取Url查詢參數(shù) 公共方法
*/
function getParams(name, href) {
var href = href || window.location.href,
value = '';
if (name) {
var reg = new RegExp(name + '=([^&]*)', 'g');
href.replace(reg, function($0, $1) {
value = decodeURI($1);
});
} else {
value = {};
var reg = /\b(\w+)=([^\/&]*)/g;
href.replace(reg, function($0, $1, $2) {
value[$1] = decodeURI($2);
});
}
return value;
};
//idB中就是獲取的A頁面帶過來的id
var idB = getParams("id");