You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce双变体同步问题求助:首变体选择同步至次变体

解决WooCommerce双变体组同步问题

原代码核心问题是仅同步了当前触发变化的单个下拉框,而非所有变体属性的选中状态,同时存在选择器和字符串拼接的细节问题。以下是修正后的代码:

jQuery(document).ready(function($) {
    // 定位两组变体容器
    const $firstVariation = $('.elementor-product-variable:eq(0)');
    const $secondVariation = $('.elementor-product-variable:eq(1)');
    
    // 监听第一组所有变体下拉框的变化
    $firstVariation.on('change', '.variations select', function() {
        // 获取第一组所有变体属性的选中值
        $firstVariation.find('.variations select').each(function() {
            const attrName = $(this).data('attribute_name');
            const selectedVal = $(this).val();
            
            // 找到第二组对应属性的下拉框并同步选中值
            const $targetSelect = $secondVariation.find(`.variations select[data-attribute_name="${attrName}"]`);
            if ($targetSelect.length && $targetSelect.val() !== selectedVal) {
                // 仅在值不同时触发,避免循环触发事件
                $targetSelect.val(selectedVal).trigger('change');
            }
        });
    });
});

关键修复点

  • 同步所有属性:不再只处理当前变化的单个下拉框,而是遍历第一组所有变体选择器,确保所有属性的选中状态都同步到第二组
  • 选择器与字符串拼接:使用模板字符串替代HTML实体转义,避免引号冲突,同时增加元素存在性检查,防止找不到元素报错
  • 避免循环触发:判断目标下拉框当前值与要设置的值是否不同,再触发change事件,防止反向同步导致的死循环

额外注意:

  • 确认Elementor变体容器类名确实是elementor-product-variable,如果不是,需替换为实际容器类(比如.elementor-widget-woocommerce-product-variable)
  • 两组变体的属性名称(data-attribute_name)必须完全一致,才能准确匹配对应下拉框

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 01:07:07