JQuery/Javascript 和 && 运算符的使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10261150/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:32:39  来源:igfitidea点击:

JQuery/Javascript and the use of && operators

javascriptjqueryoperators

提问by mrEmpty

I'm trying to get a simple conditional statement to work, and running into problems. The failing code:

我试图让一个简单的条件语句起作用,但遇到了问题。失败的代码:

    $(document).ready(function(){
    var wwidth = $(window).width();

    if (wwidth < 321) {
        alert("I am 320 pixels wide, or less");
        window.scrollTo(0,0);
    } else if (wwidth > 321) && (wwidth < 481) {
        alert("I am between 320 and 480 pixels wide")
    }
});

If I remove the else if part of the code, I get the alert. If I try to use && or || operators it will fail. I've Googled, I can't find a reason why it's not working. I've also tried:

如果我删除代码的 else if 部分,我会收到警报。如果我尝试使用 && 或 || 运营商它会失败。我用谷歌搜索过,我找不到它不起作用的原因。我也试过:

((wwidth > 321 && wwidth < 481))

along with other ways, just in case it's some odd syntax thing.

以及其他方式,以防万一它是一些奇怪的语法事情。

Any help would be greatly appreciated. Thanks :)

任何帮助将不胜感激。谢谢 :)

回答by Mikey

((wwidth > 321) && (wwidth < 481))

This is the condition you need (http://jsfiddle.net/malet/wLrpt/).

这是您需要的条件(http://jsfiddle.net/malet/wLrpt/)。

I would also consider making your conditions clearer like so:

我也会考虑让你的条件更清晰,如下所示:

if (wwidth <= 320) {
    alert("I am 320 pixels wide, or less");
    window.scrollTo(0,0);
} else if ((wwidth > 320) && (wwidth <= 480)) {
    alert("I am between 320 and 480 pixels wide")
}

回答by Jonny Burger

if (wwidth > 321 && wwidth < 481) {
//do something
}

回答by ron tornambe

There are two issues. The first has already been answered, the second is "wwidth > 320" which should be "wwidth>=320". What if the window is larger than 480?

有两个问题。第一个已经得到回答,第二个是“wwidth > 320”,应该是“wwidth>=320”。如果窗口大于 480 怎么办?

you can also implement "between" as follows:

您还可以按如下方式实现“介于”:

Number.prototype.between = function(a, b) {
  return this >= a && this <= b
}

$(document).ready(function(){
    var wwidth = $(window).width();
    if (wwidth < 321) {
      alert("I am 320 pixels wide, or less");
      window.scrollTo(0,0);
    } else if (wwidth.between(321,481))
        alert("I am between 320 and 480 pixels wide")
    else alert("I am greater than 480 pixels wide.");  
});