隐藏

EasyUI 购物车

发布:2013/5/5 15:41:56作者:管理员 来源:本站 浏览次数:1796

使用jQuery easyui,我们在web应用中就有了拖放的能力。这个教程显示了如何构建购物车页,它使用户拖放他们希望购买的产品,更新购物篮的物品和价格。
\
显示产品页:
<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>

ul元素包含一些li元素以显示产品。每一个产品的名称和单价属性在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>

使用datagrid显示购物篮项目。
拖曳产品副本
$('.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';

    }

});

我们设置draggable属性proxy为clone,所以拖曳元素使用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函数更新购物篮。