JQuery,DRY.使用ajax点击功能
JQuery, DRY. Click functions with ajax
此代码不是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);
相关文章:
- 点击功能没有'ajax调用动态元素(Backbone)后无法工作
- 检查jquery(或ajax)功能是否已完成
- 在动态功能中缓存ajax请求
- 在单模式中断功能中使用Ajax渲染部分
- codeigniter HMVC ajax上的更新功能
- Jquery&Ajax表单验证功能
- 一个Ajax函数能产生另一个Ajax功能吗
- ajax之后的reinit功能
- 无刷新功能的Ajax内容加载
- 在以下情况下,如何使用AJAX实现删除功能
- AJAX具有相同提交/单击功能的多个表单
- jquery ajax调用后,表分类器功能不起作用
- 无法使用ajax序列化功能将图像插入数据库
- jQuery移动Ajax导航功能和CSS样式
- $.ajax后功能安全性
- JQuery,DRY.使用ajax点击功能
- 当有人点击浏览器关闭按钮时,使用JavaScript或ajax功能
- ajax responseText验证功能冻结页面内容(async)
- JQuery AJAX没有't获得成功回调功能
- jQuery重新使用了ajax功能