此代码不干。 这个函数区别于一些变量和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);
}
})
});
我想以最好的方式做到这一点。怎么办?帮助我。
答案 0 :(得分:2)
编辑,因为您更改了代码
为所有ajax创建一个函数并将其绑定到两个按钮的click事件。检查单击了哪个按钮,并根据按钮确定操作:
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);