商品详情页的开发4
来自CloudWiki
增加鼠标悬停、图片变换的动作
(文件名称)detail/index.js
在bindEvent函数中添加:
var _this = this; // 图片预览 $(document).on('mouseenter', '.p-img-item', function(){ var imageUrl = $(this).find('.p-img').attr('src'); $('.main-img').attr('src', imageUrl); });
代码或结果截图:
改变商量数量的操作
(文件名称)detail/index.js 在bindEvent函数中添加:
代码:
// count的操作 $(document).on('click', '.p-count-btn', function(){ var type = $(this).hasClass('plus') ? 'plus' : 'minus', $pCount = $('.p-count'), currCount = parseInt($pCount.val()), minCount = 1, maxCount = _this.data.detailInfo.stock || 1; if(type === 'plus'){ $pCount.val(currCount < maxCount ? currCount + 1 : maxCount); } else if(type === 'minus'){ $pCount.val(currCount > minCount ? currCount - 1 : minCount); } });
在刚才加载函数loadDetail中加入缓存数据的语句:
// 加载商品详情的数据 loadDetail : function(){ var _this = this, html = '', $pageWrap = $('.page-wrap'); // loading $pageWrap.html('<div class="loading"></div>'); // 请求detail信息 _product.getProductDetail(this.data.productId, function(res){ _this.filter(res); // 缓存住detail的数据 _this.data.detailInfo = res; // render html = _mm.renderHtml(templateIndex, res); $pageWrap.html(html); }, function(errMsg){ $pageWrap.html('<p class="err-tip">此商品太淘气,找不到了</p>'); }); },
效果:
添加‘加入购物车’动作
添加‘加入购物车动作
文件:detail /index.js 在bindEvent函数中添加
// 加入购物车 $(document).on('click', '.cart-add', function(){ _cart.addToCart({ productId : _this.data.productId, count : $('.p-count').val() }, function(res){ window.location.href = './result.html?type=cart-add'; }, function(errMsg){ _mm.errorTips(errMsg); }); });
写服务端函数
文件 service /cart-service.js
// 添加到购物车 addToCart : function(productInfo, resolve, reject){ _mm.request({ url : _mm.getServerUrl('/cart/add.do'), data : productInfo, success : resolve, error : reject }); },
注:前面的函数结尾别忘了添加逗号
修改处理结果页面
Result.html添加:
<div class="result-con cart-add-success"> <h1 class="result-title">您的商品已成功加入购物车!</h1> <div class="result-content"> <a class="link" href="./index.html">继续购物</a> <a class="link" href="./cart.html">去购物车查看</a> </div> </div>