我有一件 T 恤产品,有多种尺寸和颜色可供选择。选择一个变体后,我希望在另一个变体中自动选择第一个可用选项。
例如,如果我有一件只有大号和特大号的白色 T 恤和一件只有小号和中号的绿色 T 恤,当用户选择白色时,它应该自动选择大号。但是,如果用户随后改变主意并选择绿色,它应该自动选择小。但是,只有在其他变体中没有选择可用的选项时,才会发生这种情况。
虽然我可以运行脚本来选择第一个启用的更改选项,但一旦用户再次更改为不同的颜色,WooCommerce 会发出“缺货”警告并清除他们的选择,然后我才能再次运行更改脚本。
我试图用 on 运行woocommerce_variation_select_change
,woocommerce_variation_has_changed
但show_variation
hide_variation
没有任何运气。
任何帮助将非常感激。以下是我迄今为止提出的大致内容:
$(document).on( 'change', '.variations select', function( event ) {
if ( !$(this).val() ) return false;
var select = $(this);
var variations = $(this).closest('.variations');
$(variations).find('select').not(select).each(function() {
var val = $(this).val();
if ( !val || ( val && !$(this).find('option[value='+val+']:enabled') ) ) {
$(this).find('option:enabled').each(function() {
if ( $(this).attr('value') ) {
$(this).prop('selected', 'selected');
return false;
}
});
}
});
});