[英]else if statement not working in jquery
我删除了变量名,只是为了简单起见将它们放在其中。
无法弄清楚为什么它不能正常工作, else
语句可以正常工作, if
语句可以正常工作,而else if
部分不能正常工作。
if (scrollTop > 200) {
$('.vote-next-hover').css({
position: 'fixed',
top: '50px',
width: statuscontain,
});
}
else if (scrollTop > 5500) {
$('.vote-next-hover').css({
position: 'absolute',
top: '',
width: '',
});
}
else {
$('.vote-next-hover').css({
position: 'relative',
top: '',
width: '',
});
}
滚动200px,触发if语句,向后滚动到小于200并触发else语句,但是在任何时候都不会触发else if语句。
我以为是-条件1遇难,火灾-条件2遇难,火灾-条件3遇难,火灾?
您应该交换if
和else if
子句。 请参见,如果scrollTop
值大于5500
,则它肯定大于200
因此它将很好地通过第一个检查,从而使第二个检查毫无意义。
因此, if (scrollTop > 5500)
应该在代码中排在首位,然后再进行else if (scrollTop > 200)
检查。
我不知道您是否知道可以使用... switch
编写相同的分支逻辑?
var hoverStyle = { position: 'relative', top: '', width: '' };
switch (true) {
case scrollTop > 5500:
hoverStyle.position = 'absolute';
break;
case scrollTop > 200:
hoverStyle = { position: 'fixed', top: '50px', width: statuscontain };
}
$('.vote-next-hover').css(hoverStyle);
有些人甚至认为它比if-elseif-else
更具可读性。 但当然,这里也有同样的限制-较不常见的情况应首先处理(或以后再检查)。
作为一个旁注,我真的认为在分支内复制$('.vote-next-hover').css()
调用没有意义。 仅分隔代码的不同部分就足够了-在这种情况下,设置.css()
参数。
if / else if / else块应仅运行以下三个选项之一。 例如:
var test = 4;
if (test === 4) { //true
test = 3;
} else if(test === 3) {//does not do, already did one
test = 0
} else {
test = “something”
}
因此,您需要三个if块,而不是if / else if / else。
假设您滚动到6000,则6000大于200,因此满足第一个条件。 然后,因为else if
不测试第二个条件,则有另一个。
您有两种选择:
将scrollTop> 5500 check添加到> 200 check内,或者替换if, else if
的顺序if, else if
先放置> 5500 check,然后再放置> 200 check。
if (scrollTop > 200) {
if (scrollTop > 5500) {
$('.vote - next - hover ').css({
position: 'absolute ',
top: '',
width: '',
});
} else {
$('.vote - next - hover ').css({
position: 'fixed ',
top: '50px ',
width: statuscontain,
});
}
} else {
$('.vote - next - hover ').css({
position: 'relative ',
top: '',
width: '',
});
}
“滚动200px,触发if语句,向后滚动到小于200并触发else语句,但是在任何时候都不会触发else if语句。”
这是一个逻辑错误。 因为任何高于5500的数字也高于200,并且当您使用else时,如果您说第一个条件不正确。
您应该将代码更改为:
if (scrollTop > 5500) {
$('.vote-next-hover').css({
position: 'absolute',
top: '',
width: '',
});
}
else if (scrollTop > 200) {
$('.vote-next-hover').css({
position: 'fixed',
top: '50px',
width: statuscontain,
});
}
else {
$('.vote-next-hover').css({
position: 'relative',
top: '',
width: '',
});
}
此逻辑错误
$('#crud_interval').bind("change", function() {
if( $('#crud_interval').val() ==='Daily' ) { //not running
$('#crud_weekly_day').hide();
$('#crud_monthly_date').hide();
} else if( $('#crud_interval').val() ==='Weekly' ) { //not running
$('#crud_weekly_day').show();
$('#crud_monthly_date').hide();
} else {
$('#crud_weekly_day').hide();
$('#crud_monthly_date').show();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.