jQuery on()方法绑定动态元素的点击事件-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

jQuery on()方法绑定动态元素的点击事件

小旋风柴进 2016-03-26 08:21:30 2205

我正在做一个商城相关的项目,需要用到购物车。购物车的数据我存在了session里,但是在前端需要实时更新购物车的数据,所以动态的创建了元素。
在jquery中,要给动态元素绑定事件,我使用了on方法,但是该方法一直不生效,必须刷新页面才能删除购物车的数据,请大家帮忙看看。
项目使用的是ThinkPHP框架。

<?php
/**
 * 
 * @authors tudouya (http://www.php101.cn/)
 * @date    2015-04-08 01:37:39
 * @version $1.0$
 */
namespace Mall\Controller;
use Think\Controller;

class CartController extends Controller {
    public function __construct(){
        parent::__construct();

        // session(null);
        if(!isset($_SESSION['cart'])){
            $_SESSION['cart'] = array();
        }
    }

    public function index(){
        kd($_SESSION);
    }

    public  function addItem(){
        /*
         * 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 .= '<div class="shoppingCartProductWrapper"> <a  href="' . U('mall/index/gooddetail',array('id'=>$v['good_id'])) . '" class="shoppingCartProductImageWrapper">'.'<img src="'.$v['good_image'].'" class="shoppingCartProductImage" alt=""/></a><div class="shoppingCartProductInfoWrapper"> <a href="'.U('mall/index/gooddetail',array('id'=>$v['good_id'])).'" class="shoppingCartProductTitle">'.$v['good_name'].'</a><div class="shoppingCartProductButtonsWrapper"><input type="text" id="shoppingCartProductNumber-1" class="shoppingCartProductNumber" name="product-1" value="'.$v['good_num'].'" /><span class="shoppingCartProductPrice">'.$v['good_price'].'</span><a href="javascript:void(0)" class="shoppingCartRemoveProductButton"></a> </div></div></div>';
            }
            $html .= '<div class="shoppingCartInfoWrapper"><span class="shoppingCartProductsNumber">商品数量:'.count($_SESSION['cart']) . '</span><span class="shoppingCartProductsTotal">Total: ¥'.$total_price.'</span></div>';
            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 .= '<div class="shoppingCartProductWrapper"> <a  href="' . U('mall/index/gooddetail',array('id'=>$v['good_id'])) . '" class="shoppingCartProductImageWrapper">'.'<img src="'.$v['good_image'].'" class="shoppingCartProductImage" alt=""/></a><div class="shoppingCartProductInfoWrapper"> <a href="'.U('mall/index/gooddetail',array('id'=>$v['good_id'])).'" class="shoppingCartProductTitle">'.$v['good_name'].'</a><div class="shoppingCartProductButtonsWrapper"><input type="text" id="shoppingCartProductNumber-1" class="shoppingCartProductNumber" name="product-1" value="'.$v['good_num'].'" /><span class="shoppingCartProductPrice">'.$v['good_price'].'</span><a href="javascript:void(0)" class="shoppingCartRemoveProductButton"></a> </div></div></div>';
        }
        $html .= '<div class="shoppingCartInfoWrapper"><span class="shoppingCartProductsNumber">商品数量:'.count($_SESSION['cart']) . '</span><span class="shoppingCartProductsTotal">Total: ¥'.$total_price.'</span></div>';

        exit($html);
    }

    public function removeItem(){
        $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 .= '<div class="shoppingCartProductWrapper"> <a  href="' . U('mall/index/gooddetail',array('id'=>$v['good_id'])) . '" class="shoppingCartProductImageWrapper">'.'<img src="'.$v['good_image'].'" class="shoppingCartProductImage" alt=""/></a><div class="shoppingCartProductInfoWrapper"> <a href="'.U('mall/index/gooddetail',array('id'=>$v['good_id'])).'" class="shoppingCartProductTitle">'.$v['good_name'].'</a><div class="shoppingCartProductButtonsWrapper"><input type="text" id="shoppingCartProductNumber-1" class="shoppingCartProductNumber" name="product-1" value="'.$v['good_num'].'" /><span class="shoppingCartProductPrice">'.$v['good_price'].'</span><a href="javascript:void(0)" class="shoppingCartRemoveProductButton"></a> </div></div></div>';
        }
        $html .= '<div class="shoppingCartInfoWrapper"><span class="shoppingCartProductsNumber">商品数量:'.count($_SESSION['cart']) . '</span><span class="shoppingCartProductsTotal">Total: ¥'.$total_price.'</span></div>';
        exit($html);
    }
}
?>
  <!-- shopping cart wrapper start -->
    <form id="shoppingCartWrapper" class="shoppingCartWrapper" action="#" method="post">
      <fieldset>        
        <?php 
          $total_price = 0;
          foreach($_SESSION['cart'] as $k=>$v){
            $total_price += $v['good_price']*intval($v['good_num']);
        ?>
        <!-- shopping cart product starts -->
        <div class="shoppingCartProductWrapper"> 
          <a href="<?php echo DOMAIN.'/mall/index/gooddetail/id/'.$v['good_id'].'.html'; ?>" class="shoppingCartProductImageWrapper">
            <img src="<?php echo $v['good_image']; ?>" class="shoppingCartProductImage" alt=""/>
          </a>
          <div class="shoppingCartProductInfoWrapper"> 
            <a href="<?php echo DOMAIN.'/mall/index/gooddetail/id/'.$v['good_id'].'.html'; ?>" class="shoppingCartProductTitle"><?php echo $v['good_name']; ?></a>
            <div class="shoppingCartProductButtonsWrapper">
              <input type="text" class="shoppingCartProductNumber" name="product-3" value="<?php echo $v['good_num']; ?>"/>
              <input type="hidden" name="good_id" value="<?php echo $v['good_id']; ?>" />
              <span class="shoppingCartProductPrice">¥<?php echo $v['good_price']; ?></span><a href="javascript:void(0)" class="shoppingCartRemoveProductButton"></a> </div>
          </div>
        </div>
        <!-- shopping cart product ends --> 
        <?php } ?>

        <!-- shopping cart info wrapper starts -->
        <div class="shoppingCartInfoWrapper"> 
          <span class="shoppingCartProductsNumber">商品数量: <?php echo count($_SESSION['cart']); ?></span> 
          <span class="shoppingCartProductsTotal">Total: ¥<?php echo $total_price; ?></span> 
        </div>
        <!-- shopping cart info wrapper ends -->

        <div id="shoppingCartButtons" class="shoppingCartButtonsWrapper"><a href="" class="shoppingCartEmptyButton">清空</a>
          <input type="submit" value="去付款" id="shoppingCartCheckoutButton" class="shoppingCartCheckoutButton"/>
        </div>
      </fieldset>
    </form>
    <!-- shopping cart wrapper ends --> 
    <script type="text/javascript">
        $(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);
              }
            });
          });
        });
    </script>
元素绑定 元素的方法 jquery绑定 元素点击事件 元素事件
分享到
取消 提交回答
全部回答(1)
  • 小旋风柴进
    2019-07-17 19:15:03

    对于动态绑定元素可以这样写

    $(document).on('click', '.xxx', function() {
       // do something
    });

    $(document)可以改成要绑定事件元素的父节点

    .xxx 就是指的当前元素

    这样就可以实现事件的代理

    0 0
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

相似问题
最新问题