简体   繁体   中英

jQuery if / else if statement priorities

I am trying to understand why my code does not work the way I want it to. In the comments I am expalaining what each part means.

Here is my code:

$(document).keyup(function(event){
    // if hit > arrow key
    if(event.keyCode == 39){

      // if nav's level 1 dropdown list is not displayed, use > arrow in level 0
      if ($('nav li .sub-menu').css('display', 'none')){
        $('nav li.active').next().addClass('active').siblings().removeClass('active');


      // else if level 1 dropdown list is displayed, use > arrow in level 1
      }else if ($('nav li.active .sub-menu').css('display', 'block') && $('nav .sub-menu li').hasClass('has-child')){ 


         // open level 2 dropdown list
         $('nav li.active .sub-menu li.has-child').find('.sub-sub-menu').stop().hide(); 
      }
    }        
});

The problem is, it does not go into else if statement, no matter if dropdown list is displayed or not, therefore > arrow keeps working in level 0 (nav). If I use if statement instead else if, > arrow works both in level 0 and level 1, and its not what I am looking for.

If anyone knows whats wrong with my code, I would appreciate to hear your answer. Thank you.

$('nav li .sub-menu').css('display', 'none') sets the display to none , it does not check its value. That is why it is not working.

What you want to do is:

if($('nav li .sub-menu').css('display') === 'none)

The same goes for the else statement. You should have something like this instead:

$(document).keyup(function(event){
    // if hit > arrow key
    if(event.keyCode == 39){
      var nav = $('nav li .sub-menu');
      var navDisplay = nav.css('display');

      // if nav's level 1 dropdown list is not displayed, use > arrow in level 0
      if (navDisplay === 'none'){
        $('nav li.active').next().addClass('active').siblings().removeClass('active');


      // else if level 1 dropdown list is displayed, use > arrow in level 1
      }else if (navDisplay === 'block' && nav.hasClass('has-child')){ 


         // open level 2 dropdown list
         $('nav li.active .sub-menu li.has-child').find('.sub-sub-menu').stop().hide(); 
      }
    }        
});

Try to get into the habit of storing the results of your jQuery calls if you know you are going to reuse them, these DOM calls can get pretty expensive.

You have several options here.

You can do:

if($('nav li .sub-menu').css('display') === 'none'))

OR

if($('nav li .sub-menu:visible'))

OR

if($('nav li .sub-menu').is(":visible")))

The last one is the prettiest and pretty standard.

you are setting the display not checking the state. try this to check if your element is hidden or not

$('nav li.active .sub-menu').is(":visible") 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM