javascript 否则如果不工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20517153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Else if not working
提问by Ruud Schro?n
I have a function which runs through some divs, and inside each div it counts the amount of children. Then based on the amount of children (var length), it does something.
我有一个通过一些 div 运行的函数,在每个 div 中它计算子元素的数量。然后根据孩子的数量(var length),它会做一些事情。
$('.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');
}
});
The first if statement works and the else statement works. But for some reason the else if statement doesn't work, even when lengthis higher than 5 (i checked in the console log).
第一个 if 语句起作用,else 语句起作用。但是由于某种原因 else if 语句不起作用,即使长度大于 5(我检查了控制台日志)。
Does anyone know what i'm doing wrong?
有谁知道我做错了什么?
回答by Adil
Length
greater then 2
is alwaysgreater then 5
so it will always go in first if statement block. Change condition in first if
so that the else part could be executed.
Length
大于2
是始终大于5
所以它总是if语句块进去第一。首先更改条件,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');
}
回答by opalenzuela
Yes. The first if ( length>= 2) includes also the second else if (length > 5)
是的。第一个 if (length>=2) 还包括第二个 else if (length > 5)
In another words, if the first condition is met, so is the second, so the flow will never reach the second block.
换句话说,如果满足第一个条件,则满足第二个条件,因此流将永远不会到达第二个块。
You can change the code for the following (which, I believe, it's easier to understand):
您可以更改以下代码(我相信这更容易理解):
if (length >5){
console.log('more than five');
}
else if (length > 2){
console.log('more than two');
}
else{
console.log('single item');
}
回答by Nick
If you want both the ifs to work you just remove the else, because the else prevents the second if to be executed:
如果您希望两个 if 都起作用,只需删除 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');
}
});