一. 問題背景
-
點擊商品展示頁,能另外打開新標籤跳轉到商品詳情頁,效果如下:
-
前臺:使用到的頁面全是html沒有jsp,所以這裏是在html之間傳值,從商品展示頁傳遞商品id到商品詳情頁
二. 解決方案
2.1 思路
- 給
<a>
綁定onclick事件 - 定義一個處理跳轉的函數
2.2 關鍵代碼
最最最最最關鍵的是window.open('xxxxxxxxxxxxx.html');
- mallIndex.html商品詳情頁,product_id是已經被賦值了的變量,將此值傳給商品詳情頁,如下:
<a onclick='to(product_id)'></a>
<script>
window.to = function (id){
window.open('productDetail.html?product_id='+id);
}
</script>
解釋:
- 如果上面用window.location.href而不是window.open,那麼將不會打開新的標籤頁進行跳轉,而是在當前標籤頁進行跳轉。
window.open
的作用有target='_blank'
的功能 - 上面定義函數用window.to = function (){} 而不是function to(){},如果採用後者,那麼點擊
<a>
後則會出現Uncaught ReferenceError: xxx is not defined
報錯
- productDetail.html商品詳情頁,最最最最關鍵是用
window.location.search()
,如下:
<script>
var product_id = oneValue();
//接收單個值
function oneValue(){
var result;
var url = window.location.search();//獲取url中“?”後面的字符串
if(url.length != -1){
result = url.substr(url.indexOf("=")+1);
console.info("result:" + result);//按瀏覽器F12,打印出來
}
return result;
}
</script>