一. 问题背景
-
点击商品展示页,能另外打开新标签跳转到商品详情页,效果如下:
-
前台:使用到的页面全是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>