JQuery/Javascript and the use of && operators

前端 未结 3 1282
旧巷少年郎
旧巷少年郎 2020-12-31 16:25

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

    $(document).ready(function(){
    var wwidth = $         


        
相关标签:
3条回答
  • 2020-12-31 16:51

    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?

    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.");  
    }); 
    
    0 讨论(0)
  • 2020-12-31 17:00
    if (wwidth > 321 && wwidth < 481) {
    //do something
    }
    
    0 讨论(0)
  • 2020-12-31 17:11
    ((wwidth > 321) && (wwidth < 481))
    

    This is the condition you need (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")
    }
    
    0 讨论(0)
提交回复
热议问题