六 20
easyUI 教程 » 创建拖拽购物车
如果在你的web应用中轻松实现拖拽和释放,你会发现你获得一些不同的东西。使用jQuery EasyUI ,我们可以在web应用中加入拖拽和释放功能。
在本教程中,我们将向您展示如何创建购物车,用户可以将他们希望购买的商品拖拽到购物车并释放。购物车商品数量和价格会自动更新。

创建拖拽购物车 Building a drag-drop shopping cart
在页面上展示商品:
<ul class="products">
<li>
<a href="#" class="item">
<img src="shirt1.gif"/>
<div>
<p>Balloon</p>
<p>Price:$25</p>
</div>
</a>
</li>
<li>
<a href="#" class="item">
<img src="shirt2.gif"/>
<div>
<p>Feeling</p>
<p>Price:$25</p>
</div>
</a>
</li>
<!-- other products -->
</ul>
在上述代码中,我们添加了一个包含多个<li>元素的<ul>元素来展示商品。每个商品都有包含在<p>标签中的名称和价格属性。
创建购物车:

<div class="cart">
<h1>Shopping Cart</h1>
<table id="cartcontent" style="width:300px;height:auto;">
<thead>
<tr>
<th field="name" width=140>Name</th>
<th field="quantity" width=60 align="right">Quantity</th>
<th field="price" width=60 align="right">Price</th>
</tr>
</thead>
</table>
<p class="total">Total: $0</p>
<h2>Drop here to add to cart</h2>
</div>
我们使用数据表格来展示购物车商品项。
拖拽要克隆的商品:
$('.item').draggable({
revert:true,
proxy:'clone',
onStartDrag:function(){
$(this).draggable('options').cursor = 'not-allowed';
$(this).draggable('proxy').css('z-index',10);
},
onStopDrag:function(){
$(this).draggable('options').cursor='move';
}
});
注意:我们设置拖拽属性’proxy’为’clone’,因此拖拽的元素将有克隆效果。
释放选择的商品到购物车:
$('.cart').droppable({
onDragEnter:function(e,source){
$(source).draggable('options').cursor='auto';
},
onDragLeave:function(e,source){
$(source).draggable('options').cursor='not-allowed';
},
onDrop:function(e,source){
var name = $(source).find('p:eq(0)').html();
var price = $(source).find('p:eq(1)').html();
addProduct(name, parseFloat(price.split('$')[1]));
}
});
////////////////////////////////////////////////
var data = {"total":0,"rows":[]};
var totalCost = 0;
function addProduct(name,price){
function add(){
for(var i=0; i<data.total; i++){
var row = data.rows[i];
if (row.name == name){
row.quantity += 1;
return;
}
}
data.total += 1;
data.rows.push({
name:name,
quantity:1,
price:price
});
}
add();
totalCost += price;
$('#cartcontent').datagrid('loadData', data);
$('div.cart .total').html('Total: $'+totalCost);
}
当释放商品到购物车时,我们首先获取商品的名称和价格,然后调用’addProduct’方法来更新购物车。
下载购物车实例代码: easyui-shopping-demo.zip
最新评论