2016-04-04 2 views
-2

Этот код не является СУХОЙ. Эти функции отличаются некоторыми переменными и 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

функцию привязки, как '$ нажмите (функция() {. 'ie [Multiple Selector (« selector1, selector2, selectorN »)] (https://api.jquery.com/multiple-selector/) – Satpal

+0

@timgeb Это делает его просто« слишком широким »на SO. Закройте причину. – Mast

+0

Пожалуйста, сделайте * not * use «принадлежит на сайте X» в качестве близкой причины. Существование другого сайта не делает здесь что-то не так. Оно может быть слишком широким (в этот момент вы можете быть полезны, указав на другой сайт), но, пожалуйста, придерживайтесь наших * обычных * не по теме. –

ответ

2

Edit, так как вы изменили код

Сделать функцию для всех ваших АЯКС вещи и связать его с события нажатия обеих кнопок. Проверьте, какая кнопка была нажата и в зависимости от кнопки, определяют действия: («увеличить-постатейный, .decrease-постатейный»)

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 !! Это работает! Спасибо тебе друг. Вы мне очень помогли. –

Смежные вопросы