使用layui實現從商品展示跳轉到商品詳情頁,上一頁html跳轉到另外一頁html,前端值在頁面之間的傳遞

一. 問題背景

  • 點擊商品展示頁,能另外打開新標籤跳轉到商品詳情頁,效果如下:
    在這裏插入圖片描述

  • 前臺:使用到的頁面全是html沒有jsp,所以這裏是在html之間傳值,從商品展示頁傳遞商品id到商品詳情頁

二. 解決方案

2.1 思路

  1. <a>綁定onclick事件
  2. 定義一個處理跳轉的函數

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>

解釋:

  1. 如果上面用window.location.href而不是window.open,那麼將不會打開新的標籤頁進行跳轉,而是在當前標籤頁進行跳轉。window.open的作用有target='_blank'的功能
  2. 上面定義函數用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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章