我当前正在尝试提示用户为包装选择6瓶,因此如果他们不这样做则禁用按钮,但如果这样做则重新启用按钮。我面临的问题是,一旦禁用了按钮,就无法启用它,还有其他合适的功能要使用吗?尝试过event.preventDefault()也没有帮助。我的代码:
var atc = document.getElementsByName("add-to-cart");
const button = document.querySelector('button');
var selects = [...document.getElementsByTagName("select")];
document.onchange = () => {
const sum = selects.reduce((total, select) => {
return total + Number(select.selectedOptions[0].value)
}, 0);
if (sum != 6){
atc[0].addEventListener('click',function(e){
event.returnValue = false;
});
alert("You are Required to Select a Total of 6 Bottles");
}
if(sum == 6 ){
alert("You have selected 6 bottles");
atc[0].addEventListener('click',function(e){
event.returnValue = true;
});
}
};
答案 0 :(得分:0)
代替禁用按钮,您可以简单地使用运行总计来确定单击按钮时应发生的情况。
atc[0].addEventListener('click',function(e){
if(sum != 6){
alert("You are Required to Select a Total of 6 Bottles");
}
else{
//submit or whatater
}
});
答案 1 :(得分:0)
更新:已通过使用atc.disabled = true ||对其进行了修复。错误
源解决方案:Conditionally Enabling and Disabling DOM Elements
var atc = document.getElementsByName("add-to-cart");
const button = document.querySelector('button');
var selects = [...document.getElementsByTagName("select")];
document.onchange = () => {
const sum = selects.reduce((total, select) => {
return total + Number(select.selectedOptions[0].value)
}, 0);
if (sum != 6){
atc[0].disabled = true;
alert("You are Required to Select a Total of 6 Bottles");
}
if(sum == 6 ){
alert("You have selected 6 bottles");
atc[0].disabled = false;
}
};