JQuery,DRY.使用ajax点击功能

JQuery, DRY. Click functions with ajax

本文关键字:功能 ajax 使用 DRY JQuery      更新时间:2023-12-19

此代码不是DRY。这些函数与一些变量和ajax请求不同,但它们非常相似。

$(".increase-line-item").click(function(){
  var currentLineItem = $(this).parents("tr")[0];
  var lineItemQuantity = parseInt($(lineItemQuantityElement).text());
  // ...
  $.ajax({
    url: "/line_items/increase_quantity?line_item=" + $(currentLineItem).attr("data-line-item-id"),
    type: "POST",
    success: function(result){
      $(lineItemQuantityElement).text(lineItemQuantity+1);
      $(totalPriceElement).text(totalPrice);
      console.log(result);
  })
});
$(".decrease-line-item").click(function(){
  var currentLineItem = $(this).parents("tr")[0];
  var lineItemQuantity = parseInt($(lineItemQuantityElement).text());
  // ...
  $.ajax({
    url: "/line_items/decrease_quantity?line_item=" + $(currentLineItem).attr("data-line-item-id"),
    type: "POST",
    success: function(result){
      if (lineItemQuantity > 1) {
        $(lineItemQuantityElement).text(lineItemQuantity-1);
      }
      else{
        $(currentLineItem).fadeOut(200);
        $(lineItemsCountElement).text(lineItemsCount - 1);
      };
      $(totalPriceElement).text(totalPrice);
      console.log(result);
    }
  })
});

我想用最好的方式去做。怎么回事?帮帮我。

更改代码后进行编辑

为所有ajax内容创建一个函数,并将其绑定到两个按钮的单击事件。检查点击了哪个按钮,并根据按钮确定操作:

function doAjaxStuff() {
  var currentLineItem = $(this).parents("tr")[0];
  var lineItemQuantity = parseInt($(lineItemQuantityElement).text(), 10);
  var action = $(this).hasClass('increase-line-item') ? 'increase_quantity' : 'decrease_quantity';
  // ...
  $.ajax({
    url: "/line_items/" + action + "?line_item=[...]"
  })
}
$(".increase-line-item, .decrease-line-item").on('click', doAjaxStuff);