使用js+jquery+html+css开发的网站购物车插件,使用localStorage本地存储,实现购物车的商品添加、商品删除、商品修改、价格计算等。仅有前端功能,不含后端数据处理存储部分,可接入任意网站。
/*定义购物车对象*/
var cart = new Cart({
key: "cart1", //本地存储标识
list: ".cart-list", //购物车列表容器
//自定义添加事件
add: function (result) {
if (result.length == 0) {
alert("加入成功!");
} else {
console.log(result);
alert("商品已存在!");
}
},
//自定义保存事件
save: function (result) {
location = "trade/view/?id=" + result.id; //跳转订单详情页
}
});
/*预载入数据
cart.add([
{ "id": "1", "price": "20.50", "count":"2", "title": "商品1", "icon": "img.jpg", "url": "#", "stock": "10" },
{ "id": "3", "price": "15.55", "count":"5", "title": "商品3", "icon": "img.jpg", "url": "#", "stock": "10" }
]);*/
/*提交数据*/
$("form").on("submit", function () {
var $form = $(this);
var data = $form.serialize();
/*ajax
$.ajax({
url: "/trade/save",
data: data,
dataType: "json"
}).done(function (result) {
cart.save(result); //回调保存事件,result返回订单号,格式:{ "id": "***" }
}).fail(function (err) {
alert("error");
});
*/
/*测试输出*/
console.log(data);
cart.save({ "id": "1000000001" });
return false;
});
<h3>购物车</h3>
<table>
<thead>
<tr>
<th>商品</th>
<th>名称</th>
<th>价格</th>
<th>数量</th>
<th>合计</th>
<th>操作</th>
</tr>
</thead>
<tbody class="cart-list">
<tr class="cart-row">
<td>
<img src="" alt="" />
<input name="ID" type="hidden" value="[id]" />
<input name="Price" type="hidden" value="[price]" class="cart-price" />
<input name="Stock" type="hidden" value="[stock]" />
</td>
<td><a href="[url]" target="_blank">[title]</a></td>
<td><span class="cart-price-text">[price]</span></td>
<td>
<button value="-1" class="cart-minus">-</button>
<input name="Count" type="text" value="[count]" size="3" class="cart-count" />
<button value="1" class="cart-plus">+</button>
</td>
<td><span class="cart-subtotal">0</span></td>
<td><a href="javascript:;" class="cart-remove">删除</a></td>
</tr>
<tr class="cart-row-null">
<td colspan="10">暂无商品</td>
</tr>
</tbody>
</table>
<h4 style="float:left;">已选 <span class="cart-counts"></span> 件商品,<a href="javascript:;" class="cart-empty">清空购物车</a></h4>
<h4 style="text-align:right; color:#ff0000;">金额:<span class="cart-total"></span></h4>
<h3>收货信息</h3>
<table style="text-align:left;">
<tr>
<td>
姓名:<input type="text" name="name" value="小图" />
</td>
<td>
地址:<input type="text" name="address" value="青岛" />
</td>
<td>
电话:<input type="text" name="phone" value="0532-00000000" />
</td>
</tr>
</table>
<p><button type="submit">保存订单</button></p>
扫一扫关注我们
访问手机版