我有一些更大的表格,里面有很多 radio 和复选框,等等。我正在执行多项检查以根据用户输入返回不同的消息。我对此表示同意。总共有 9 种不同的场景,我目前将它们存储为 true 或 false 在单个变量中:
var scenario_one;
var scenario_two;
var scenario_three;
var scenario_four;
var scenario_five;
var scenario_six;
var scenario_seven;
var scenario_eight;
var scenario_nine;
$('input:radio[name="opt1"]').change(function(){
if($(this).val() == 'Yes'){
scenario_one = true;
} else {
scenario_one = false;
};
});
// ... and so on until all scenarios are checked ...
现在我的问题是:我如何检查是否有两个或多个变量设置为“true”?所以我可以执行这样的操作:
$('.button').click(function(){
if ( /* Check if 2 oder more of var are set true */ ){
alert('Some nice alert message');
};
});
感觉这应该不会太困难,但我对此已经没有想法了。
最佳答案
最好用 bool 数组替换变量来动态控制。
/*Replace all your variables with this*/
var scenarios = []
$('input:radio[name="opt1"]').change(function(){
/* This will assign true/false to scenario[1]*/
scenario[1] = ($(this).val() == 'Yes');
});
/* so on for the other scenarios*/
/* Then, when you need it... */
if (countTrue(scenario) >= 2) {
alert("Two or more scenarios are true!");
}
其中 countTrue
是
function countTrue(arr) {
var count = 0;
arr.forEach(function(el){
if(el){
count += 1;
}
}
return count;
}
关于jquery - 如何检查两个或多个变量是否设置为 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33439854/