duanduo0520 2017-05-24 09:58
浏览 36
已采纳

Ajax刷新后的事件监听器

I have a checkout section on my site, and I'm running this event listener on the quantity section so that every time the quantity updates based on the product clicked, the whole div reloads using AJAX (so all prices, total amounts refresh too)

The code works once but after that, the function doesnt work anymore.

$(".cart-product-quantity").bind('keyup mouseup', function () {
  console.log("working");
  var id = $(this).attr("name");
  var quantity = $(this).val();
  $.ajax({
      url: 'assets/processes/updateCartQuantities.php',
      type: 'POST',
      data: {'id': id, 'quantity' : quantity},
      success: function(data) {
        $('.checkout-table-outer').load(document.URL +  ' .checkout-table');
      }
    }); // end ajax call
});

I'm certain its due to the fact that i'm refreshing the section where .cart-product-quantity is located, but how do i get around it so that it will work every time?

Thanks

  • 写回答

1条回答 默认 最新

  • duanchi5078 2017-05-24 10:02
    关注

    What I see is you are binding event to the .cart-product-quantity but somehow the element is getting lost on your refresh. You need to use event delegation in that case for dynamic elements.

    Explanation:

    $(".cart-product-quantity").bind('keyup mouseup', function () {...
    

    So, what your code was doing is it select the elements with class .cart-product-quantity and binds the passed function to the events provided 'keyup mouseup' directly to the elements

    But as you are updating the DOM in your ajax call the elements are getting recreated again although they have same html structure and classes they are not same in the memory. These elements are new elements and as you have never binded any events to these newly created elements the events are never called.

    For these types of dynamic elements binding events to them will not work.

    You need to use Event Delegation

    Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

    Now,

    $(document).on('keyup mouseup', ".cart-product-quantity", function () {...
    

    What above code is doing is it adds event to the document and it delegates the events to it decedents using the selector ".cart-product-quantity". Here document is not getting refreshed and its there always so, it can receive these events and dynamically select its decedents using selector and trigger events on them.

    As, these delegation happens dynamically. it selects any newly created decedents also thus it is able to trigger events on your refreshed elements.

    Try using this jquery

    $(document).on('keyup mouseup', ".cart-product-quantity", function () {
      console.log("working");
      var id = $(this).attr("name");
      var quantity = $(this).val();
      $.ajax({
          url: 'assets/processes/updateCartQuantities.php',
          type: 'POST',
          data: {'id': id, 'quantity' : quantity},
          success: function(data) {
            $('.checkout-table-outer').load(document.URL +  ' .checkout-table');
          }
        }); // end ajax call
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害