您应该有隐藏的下拉列表,其中包含所有变体和可见的下拉列表或每个选项。例如:
请添加以下代码,而不是隐藏选择的代码:
{% unless product == empty %}
<script type="application/json" id="ProductJson">
{{ product | json }}
</script>
{% endunless %}
{% unless product.options.size == 1 and product.variants[0].title == 'Default Title' %}
{% for option in product.options_with_values %}
<div class="selector-wrapper js product-form__item">
<label {% if option.name == 'default' %}class="label--hidden" {% endif %}for="SingleOptionSelector-{{ forloop.index0 }}">
{{ option.name }}
</label>
<select class="single-option-selector single-option-selector product-form__input" id="SingleOptionSelector-{{ forloop.index0 }}" data-index="option{{ forloop.index }}">
{% for value in option.values %}
<option value="{{ value | escape }}"{% if option.selected_value == value %} selected="selected"{% endif %}>{{ value }}</option>
{% endfor %}
</select>
</div>
{% endfor %}
{% endunless %}
<select name="id" id="ProductSelect" data-section="{{ section.id }}" class="product-form__variants no-js" style="display:none;">
{% for variant in product.variants %}
{% if variant.available %}
<option {% if variant == product.selected_or_first_available_variant %} selected="selected" {% endif %} value="{{ variant.id }}">
{{ variant.title }}
</option>
{% else %}
<option disabled="disabled">{{ variant.title }} - {{ 'products.product.sold_out' | t }}</option>
{% endif %}
{% endfor %}
</select>
此外,您还需要添加此JS,当您更改产品选项的可见下拉列表时,它将更改隐藏的选择值:
$(document).ready(function() {
$('.single-option-selector').on(
'change',
function() {
var selectedValues = $.map(
$('.single-option-selector'),
function(element) {
var $element = $(element);
var type = $element.attr('type');
var currentOption = {};
if (type === 'radio' || type === 'checkbox') {
if ($element[0].checked) {
currentOption.value = $element.val();
currentOption.index = $element.data('index');
return currentOption;
} else {
return false;
}
} else {
currentOption.value = $element.val();
currentOption.index = $element.data('index');
return currentOption;
}
}
);
var product = JSON.parse(
document.getElementById('ProductJson').innerHTML
);
var variant = product.variants.filter(function(v) {
var condition = selectedValues.every(function(values) {
return v[values.index] == values.value;
});
return condition;
});
if (variant != null && variant.length == 1) {
$('#ProductSelect').val(variant[0].id);
}
else {
//disable add to cart button
}
}
);
});