我正在做一个商城相关的项目,需要用到购物车。购物车的数据我存在了session里,但是在前端需要实时更新购物车的数据,所以动态的创建了元素。在jquery中,要给动态元素绑定事件,我使用了on方法,但是该方法一直不生效,必须刷新页面才能删除购物车的数据,请大家帮忙看看。项目使用的是ThinkPHP框架。/****@authorstudouya(http://www.php101.cn/)*@date2015-04-0801:37:39*@version$1.0$*/namespaceMall\Controller;useThink\Controller;classCartControllerextendsController{publicfunction__construct(){parent::__construct();//session(null);if(!isset($_SESSION['cart'])){$_SESSION['cart']=array();}}publicfunctionindex(){kd($_SESSION);}publicfunctionaddItem(){/**TODO---安全方面的考虑*/$good_id=intval(I('post.good_id'));if(isset($_SESSION['cart'][$good_id])){$_SESSION['cart'][$good_id]['good_num']+=1;$html='';$total_price=0;foreach($_SESSION['cart']as$k=>$v){$total_price+=$v['good_price']*$v['good_num'];$html.='$v['good_id'])).'"class="shoppingCartProductImageWrapper">'.' $v['good_id'])).'"class="shoppingCartProductTitle">'.$v['good_name'].' '.$v['good_price'].'
}$html.='商品数量:'.count($_SESSION['cart']).' Total:¥'.$total_price.'
exit($html);}$good_name=I('post.good_name');$good_price=I('post.good_price');$good_image=I('post.good_image');$good_num=intval(I('post.good_num'));$good=compact('good_id','good_name','good_price','good_image','good_num');$_SESSION['cart'][$good_id]=$good;$html='';$total_price=0;foreach($_SESSION['cart']as$k=>$v){$total_price+=$v['good_price']*$v['good_num'];$html.='$v['good_id'])).'"class="shoppingCartProductImageWrapper">'.' $v['good_id'])).'"class="shoppingCartProductTitle">'.$v['good_name'].' '.$v['good_price'].'
}$html.='商品数量:'.count($_SESSION['cart']).' Total:¥'.$total_price.''; exit($html);}publicfunctionremoveItem(){$good_id=intval(I('post.good_id'));unset($_SESSION['cart'][$good_id]);$html='';$total_price=0;foreach($_SESSION['cart']as$k=>$v){$total_price+=$v['good_price']*$v['good_num'];$html.='$v['good_id'])).'"class="shoppingCartProductImageWrapper">'.' $v['good_id'])).'"class="shoppingCartProductTitle">'.$v['good_name'].' '.$v['good_price'].' '; }$html.='商品数量:'.count($_SESSION['cart']).' Total:¥'.$total_price.''; exit($html);}}?> $(function(){remove_url="{:U('mall/cart/removeitem')}";$('#shoppingCartWrapper').find('.shoppingCartRemoveProductButton').on('click',function(){good_id=$(this).prev().prev().val();$.ajax({'url':remove_url,'type':'post','data':{'good_id':good_id},'success':function(data){$('#shoppingCartButtons').prevAll().remove();$('#shoppingCartButtons').before(data);}});});});线上演示地址:http://weixin.chenfw.me/mall/index慕斯709654浏览 298回答 22回答
撒科打诨
对于动态绑定元素可以这样写$(document).on('click','.xxx',function(){//dosomething});$(document)可以改成要绑定事件元素的父节点.xxx就是指的当前元素这样就可以实现事件的代理随时随地看视频慕课网APP相关分类