2016-04-04 11 views
-2

このコードはDRYではありません。 この関数はいくつかの変数とajax要求が異なりますが、非常に似ています。JQuery、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); 
    } 
    }) 
}); 

私はそれを最善の方法で行いたいと考えています。それはどうですか?助けて。あなたのコードを変更し

+1

バインド機能(機能をクリックします。クリックされたボタンをチェックして、ボタンに応じて、アクションを決定する(「-増加ライン項目、.decreaseライン項目。」)。つまり、[Multiple Selector( "selector1、selector2、selectorN")](https://api.jquery.com/multiple-selector/) – Satpal

+0

@timgebこれは単に「あまりにも広すぎる」ようにしています。閉じる理由。 – Mast

+0

「サイトXに属していません」というのは、近くの理由として別のサイトが存在していても、ここでは話題にならないということです。サイトを参照してください)。しかし、通常の*オフトピックの理由に従ってください。 –

答えて

2

編集以来

は、すべての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); 
+0

機能のためにajaxリクエストが異なる –

+0

Yess !!それは仕事です!ありがとう、友よ。あなたは私をたくさん助けました。 –

関連する問題