我有一个贯穿一些div的函数,在每个div中它计算了孩子的数量。然后根据子项的数量(var 长度),它会做一些事情。
$('.member-type').each(function() {
var length = $(this).children('.views-row').length;
if (length >= 2){
console.log('equal to or more than two');
}
else if (length > 5){
console.log('more than five');
}
else{
console.log('single item');
}
});
第一个if语句有效,else语句有效。但由于某种原因,即使长度高于5(我在控制台日志中检查过),else if语句也不起作用。
有谁知道我做错了什么?
答案 0 :(得分:6)
Length
大于2
始终大于5
因此,如果语句阻止,它将始终位于第一位。在第一个if
中更改条件,以便可以执行else部分。
if (length >= 2 && length <= 5){
console.log('more than two and less than five');
}
else if (length > 5){
console.log('more than five');
}
else{
console.log('single item');
}
答案 1 :(得分:4)
是。第一个if(长度> = 2)还包括第二个if if(length> 5)
换句话说,如果满足第一个条件,那么第二个条件也是如此,因此流程永远不会到达第二个块。
您可以更改以下代码(我相信,这更容易理解):
if (length >5){
console.log('more than five');
}
else if (length > 2){
console.log('more than two');
}
else{
console.log('single item');
}
答案 2 :(得分:0)
如果你想要两个ifs工作,你只需删除else,因为else会阻止第二个if执行:
$('.member-type').each(function() {
var length = $(this).children('.views-row').length;
if (length >= 2){
console.log('equal to or more than two');
}
if (length > 5){
console.log('more than five');
}
else{
console.log('single item');
}
});