使用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>
发布了345 篇原创文章 · 获赞 20 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_40634846/article/details/105049346