我正在尝试根据 2 个单独的选择字段值显示/隐藏购物车按钮。
我的逻辑是这样的:
如果 selectId #pa_custom-engraving = 'no'
或 selectId #pa-color != 'custom-print'
,则显示购物车按钮。否则我想隐藏购物车。
这是我到目前为止所拥有的,除非您继续切换选择字段,否则它们会相互抵消。如何将其组合成正确的“OR”条件语句?
JS
document.getElementById('pa_custom-engraving').addEventListener('change', function () {
var style = this.value == 'no' ? 'block' : 'none';
document.getElementsByClassName('woocommerce-variation-add-to-cart')[0].style.display = style;
});
document.getElementById('pa_color').addEventListener('change', function () {
var pstyle = this.value !== 'custom-print' ? 'block' : 'none';
document.getElementsByClassName('woocommerce-variation-add-to-cart')[0].style.display = pstyle;
});
HTML
<select id="pa_custom-engraving">
<option value="">Choose an option</option>
<option value="no">No</option>
<option value="yes">Yes</option>
</select>
<select id="pa_color">
<option value="">Choose an option</option>
<option value="black">Black</option>
<option value="white">White</option>
<option value="custom-print">Custom Print</option>
</select>
最佳答案
向两个选择添加相同的监听器。更改时,查看两个选择值,并应用由 ||
分隔的条件:
const cartButton = document.querySelector('.woocommerce-variation-add-to-cart');
const selects = ['#pa_custom-engraving', '#pa_color'].map(c => document.querySelector(c));
for (const select of selects) {
select.addEventListener('change', () => {
const displayStyle= selects[0].value === 'no' || selects[1].value !== 'custom-print'
? 'block'
: 'none';
cartButton.style.display = displayStyle;
});
}
关于javascript - 对条件语句使用两个单独的选择字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60144171/