JQuery DataTables - fnDrawCallback函数被执行多次

时间:2016-12-30 14:10:56

标签: datatables

我的DataTable的每一行都是一个产品,每一行都有一个表单,可以在提交时将产品添加到购物篮中。如果我没有刷新页面,我认为会更优雅。我已经为fnDrawCallback添加了一个函数,但它正在执行多次 - 重绘这个表行的次数(过滤,返回到同一个表页)。

腓:

  <td class="add-to-basket-form"  id="<?php echo str_replace('/', '', $productPartCode); ?>">
    <p class="product-description-mobile visible-xs"><?php echo $productDescription; ?></p>
    <p class="product-partcode-mobile visible-xs"><?php echo $productPartCode; ?></p>
    <p class="product-price-mobile visible-xs">£<?php echo $showPrice; ?></p>
    <form method="post" class="add-to-basket-submit" action="extras.php?site=<?php echo $_SESSION['basketSiteNo']; ?>&action=add&code=<?php echo $productPartCode; ?>">
      <input class="add-to-basket-qty" type="text" name="quantity" value="1" size="2"/>
      <input class="add-to-basket-description" type="text" name="description" value="<?php echo $productDescription; ?>"  style="display:none;" />
      <input class="add-to-basket-price" type="number" name="price" value="<?php echo $showPrice; ?>"  style="display:none;" />
      <input class="add-to-basket-img" type="text" name="img" value="<?php echo $productImage; ?>"  style="display:none;" />
      <input class="add-to-basket-thumb" type="text" name="thumb" value="<?php echo $productThumb; ?>"  style="display:none;" />
      <button class="add-to-basket-button" type="submit"><span class="glyphicon text-tw-red glyphicon-plus-sign"></span></button>
    </form>
</td>

JavaScript的:

$('#myDataTable').dataTable({
 "fnDrawCallback": function() {                  
   $(".add-to-basket-submit").on('submit', function() {
     var item = $(this).parent().attr('id');
     var action = $(this).attr('action');
     var quantity = parseInt($(this).children('.add-to-basket-qty').val());
     var description = $(this).children('.add-to-basket-description').val();
     var price = Number($(this).children('.add-to-basket-price').val());
     var img = $(this).children('.add-to-basket-img').val();
     var thumb = $(this).children('.add-to-basket-thumb').val();
     $.post(action, { quantity: quantity, description: description, price: price, img: img, thumb: thumb } );
     var numberOfItemsInBasket = parseInt($('.number-of-items-in-basket').html());
     var totalOfBasket = Number($('#total-of-basket').html());
     numberOfItemsInBasket = numberOfItemsInBasket + 1;
     $('.number-of-items-in-basket').html(numberOfItemsInBasket);
     totalOfBasket = totalOfBasket + (quantity*price);
     totalOfBasket = totalOfBasket.toFixed(2);
     $('#total-of-basket').html(totalOfBasket);
     $('#' + item).find('form').hide();
     $('#' + item).append('<div class="in-basket-info">in basket</div>');
     return false;
   });
 }
});

描述了类似的问题here

在我的情况下使用.on没有帮助。 我还尝试将函数放在initComplete中,但这只适用于第一次绘制表时,而不是重绘表后。

请帮忙。

0 个答案:

没有答案