[英]How to fix jQuery multiple else if statements not working
I am trying to run this function but it doesn't reach the first else if when I reach the specified screen size, it will continue to use the first if.我正在尝试运行此函数,但它不会到达第一个 else 如果当我达到指定的屏幕大小时,它将继续使用第一个 if。
$(window).resize(function() {
function removeClass() {
$('#cookbook_add').removeClass('st-remove-label');
$('#email_page').removeClass('st-remove-label');
}
function addClass() {
$('#cookbook_add').addClass('st-remove-label');
$('#email_page').addClass('st-remove-label');
}
function addRemoveLabel() {
lastWidth = $(window).width();
if (lastWidth < 1150) {
console.log('1150');
addClass();
} else if (lastWidth < 975) {
console.log('975');
removeClass();
} else if (lastWidth < 680) {
console.log('680');
addClass();
} else {
removeClass();
}
}
addRemoveLabel();
});
I expect the console logs to fire when the screen is that size, but it doesn't.我希望当屏幕达到那个大小时控制台日志会触发,但事实并非如此。
You should specify a range greater than and lower than for each of the if statements您应该为每个 if 语句指定一个大于和小于的范围
$(window).resize(function() { function removeClass() { $('#cookbook_add').removeClass('st-remove-label'); $('#email_page').removeClass('st-remove-label'); } function addClass() { $('#cookbook_add').addClass('st-remove-label'); $('#email_page').addClass('st-remove-label'); } function addRemoveLabel() { lastWidth = $(window).width(); if (lastWidth < 1150 && lastWidth > 975) { console.log('1150'); addClass(); } else if (lastWidth < 975 && lastWidth > 680) { console.log('975'); removeClass(); } else if (lastWidth < 680) { console.log('680'); addClass(); } else { removeClass(); } } addRemoveLabel(); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
JSFiddle: https://jsfiddle.net/on0pet6g/ JSFiddle: https ://jsfiddle.net/on0pet6g/
The problem is that the first if will be reached with any number < 1150... so 975 is < than 1150, 680 is < than 1150.问题是第一个 if 将达到任何小于 1150 的数字......所以 975 小于 1150,680 小于 1150。
The best way is to compare the lowest values first like that:最好的方法是先比较最低值,如下所示:
if (lastWidth < 680) {
console.log('680');
addClass();
}
else if (lastWidth < 975) {
console.log('975');
removeClass();
}
else if (lastWidth < 1150) {
console.log('1150');
addClass();
}
else {
removeClass();
}
Just change the order.换个顺序就好了
Change the function to将函数更改为
function addRemoveLabel() {
lastWidth = $(window).width();
if (lastWidth <= 1150 && lastWidth > 975) {
console.log('1150');
addClass();
} else if (lastWidth <= 975 &&lastWidth > 680) {
console.log('975');
removeClass();
} else if (lastWidth <= 680) {
console.log('680');
addClass();
} else {
removeClass();
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.