You need to enable JavaScript to run this app. PrestaShop 1.7 购物车touchspin调数量至0的删除确认弹窗实现
优惠活动
大模型
产品
解决方案
定价
更多

PrestaShop 1.7 购物车touchspin调数量至0的删除确认弹窗实现

实现TouchSpin下调数量到0时的删除确认逻辑

核心实现思路

  • 找准拦截节点:PrestaShop 自带的数量调整TouchSpin组件,在数值变更完成、即将发送购物车更新请求前会触发原生change事件,这是最适合插入确认逻辑的拦截点
  • 针对性判断场景:只对从1下调到0的数值变更做拦截,正常的数量增减(比如从2改到1、从1改到2)完全走原有流程,不做额外干预
  • 最大化复用现有逻辑:弹框的文案、删除商品的触发动作完全复用已经写好的删除链接逻辑,不重复写接口请求的代码,减少兼容性问题
  • 兼容动态渲染场景:因为购物车更新后TouchSpin组件会重新渲染,要在原有updatedCart事件的回调里同步重新绑定拦截逻辑,避免绑定失效

参考代码

// 封装TouchSpin删除确认的绑定逻辑
function bindTouchSpinDeleteConfirm() {
    // 定位购物车商品行里的数量输入框(即TouchSpin的核心交互input)
    $('.cart .js-cart-line-product-quantity').each(function() {
        const $input = $(this);
        // 解绑之前绑定过的带命名空间的事件,避免重复绑定导致多次弹窗
        $input.off('change.touchspinDeleteConfirm');
        // 绑定变更后的拦截事件
        $input.on('change.touchspinDeleteConfirm', function(e) {
            const currentVal = parseInt($(this).val(), 10);
            // 仅拦截数量为0的场景
            if (currentVal === 0) {
                // 阻止默认的数量更新请求
                e.preventDefault();
                e.stopPropagation();
                // 弹出和删除链接完全一致的确认框
                if (confirm('Are you sure you want to remove product from cart?')) {
                    // 找到当前商品行对应的删除按钮,触发点击复用原有删除流程
                    const $productRow = $(this).closest('.cart-item');
                    $productRow.find('[data-link-action="confirm-remove-item"]').trigger('click');
                } else {
                    // 用户取消操作时,将输入框数值重置为1,避免出现UI和实际数据不一致
                    $(this).val(1);
                }
                return false;
            }
        })
    })
}

// 保留原有删除链接的确认逻辑
function refreshDataLinkAction() {
    $('[data-link-action="delete-from-cart"]').each(function(){
        $(this).attr('data-link-action', 'confirm-remove-item');
    });
}

$(document).on('click', '[data-link-action="confirm-remove-item"]', function(e) {
    e.preventDefault();
    if (confirm('Are you sure you want to remove product from cart?')) {
        $(this).attr('data-link-action', 'delete-from-cart');
        $(this).trigger('click');
    }
    return false;
});

$(document).ready(function () {
    refreshDataLinkAction();
    // 页面初始化时绑定TouchSpin拦截逻辑
    bindTouchSpinDeleteConfirm();
    prestashop.on('updatedCart', function () {
        refreshDataLinkAction();
        // 购物车更新完成、组件重渲染后,重新绑定拦截逻辑
        bindTouchSpinDeleteConfirm();
    });
});

落地注意事项

  • 事件绑定用了带命名空间的事件名change.touchspinDeleteConfirm,和PrestaShop自带的TouchSpin原生事件做了隔离,不会出现重复绑定导致多次弹窗、事件堆叠的问题
  • 用户点取消的时候一定要把输入框数值重置回1,否则页面上的数量输入框会停在0的状态,和购物车实际存储的数量不匹配,会造成用户困惑
  • 所有删除动作都走原有按钮的触发逻辑,不单独写接口请求代码,和PrestaShop核心的购物车更新流程保持一致,升级版本时也不容易出现兼容性问题

内容的提问来源于stack exchange,提问作者Federico

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.23 01:06:06