【问题标题】:JQuery, DRY. Click functions with ajax [closed]jQuery,干。使用ajax单击功能[关闭]
【发布时间】:2016-04-04 11:09:02
【问题描述】:

此代码不是 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);
    }
  })
});

我想以最好的方式做到这一点。它是怎么做的?帮帮我。

【问题讨论】:

  • 绑定函数如$(".increase-line-item, .decrease-line-item").click(function(){Multiple Selector (“selector1, selector2, selectorN”)
  • @timgeb 这使得它在 SO 上“太宽泛”了。无需自定义关闭原因。
  • 请不要不要使用“属于siteX”作为关闭的理由。另一个站点的存在不会使事情偏离主题。它可能过于宽泛(此时您可以通过指向另一个站点来提供帮助),但请坚持我们的通常偏离主题的原因。

标签: javascript jquery ajax dry


【解决方案1】:

在您更改代码后进行编辑

为所有 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);

【讨论】:

  • ajax 请求因功能而异
  • 是的!这是工作!谢谢你,朋友。你帮了我很多。
猜你喜欢
  • 2012-12-30
  • 1970-01-01
  • 2013-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-02
  • 1970-01-01
相关资源
最近更新 更多