php 可拖曳式,Jquery 快速构建可拖曳的购物车DragDrop

本文介绍了一种使用jQuery UI实现的拖放购物车功能。通过创建可拖动的商品元素和可放置商品的购物车区域,实现了商品的添加、移除及总价计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这样一来,购买者只需要把自己感兴趣的商品拖曳到自己的购物车中,也可以从购物车中删除商品 同时更新购物车的总体价格和数量。

那咱们就开始实例吧,本实例并没有链接数据库读取数据来初始化Products,而是创建了一些虚拟的商品如下:

1、 创建Product实体类

public class Product

{

public string Code { get; set; }

public string Name { get; set; }

public string Description { get; set; }

public double Price { get; set; }

}

[code]

2、 构建商品List

[code]

public class Product

{

public string Code { get; set; }

public string Name { get; set; }

public string Description { get; set; }

public double Price { get; set; }

}

3、创建DataList并绑定List

RepeatDirection="Horizontal" runat="server">

code='' id='item_'>

$

private void BindData()

{

var products = GetProducts();

dlProducts.DataSource = products;

dlProducts.DataBind();

}

productItemStyle 样式名称

Container.ItemIndex动态生成连续的商品编号

20091130222419200.png

4、 生成Products Div Draggable

下载最新的Jquery JS文件及其UI文件:

页面初始化时生成Div Draggable

$(document).ready(function() {

$(".productItemStyle").draggable({ helper: "clone", opacity: "0.5" });

)};

5、创建一个DropZone

DropZones 是购物车区域

$(".dropZone").droppable(

{

accept: ".productItemStyle",

hoverClass: "dropHover",

drop: function(ev, ui) {

var droppedItem = ui.draggable.clone().addClass("droppedItemStyle");

var productCode = droppedItem[0].attributes["code"].nodeValue;

var productPrice =

getFormattedPrice(droppedItem[0].attributes["price"].nodeValue);

var removeLink = document.createElement("a");

removeLink.innerHTML = "Remove";

removeLink.className = "deleteLink";

removeLink.href = "#";

removeLink.onclick = function()

{

$(".dropZone").children().remove("#" + droppedItem[0].id);

updateTotal(productPrice * (-1));

}

droppedItem[0].appendChild(removeLink);

$(this).append(droppedItem);

updateTotal(productPrice);

}

}

);

Accept参数:展示Class= “productItemStyle”的Div

hoverClass参数:当有Product放到DropZone时的样式

drop函数:当Product拖放到DropZone时出发的函数,此函数主要做了一个Product Item的Clone,价格的计算、添加Remove按钮以及到点击Remove按钮时所触发的事件。

价格的计算updateTotal()函数

// update the total!

function updateTotal(price) {

total += parseFloat(price);

$("#total").html(total.toFixed(2));

$(".shoppingCartTotal").effect("bounce");

}

最终效果如下图:

dd380c06ebdf4b69f8996f6e507dcfb0.gif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值