简体   繁体   中英

A Better Way To Write If and If Else in Jquery function

I'm certain that this block of code can be compressed to something more simple and efficient. However, I'm stumped. If anyone could help me out then that would be extremely appreciated!

var close = "true";

$(document).on('click', '[data-toggle-nav]', function(event) {


  if ($(this) && close === "true") {
    console.log('close');
    $('#top').css('transform', 'rotate(45deg)').css('top', '10px');

    $('#mid').css('transform', 'rotate(-45deg)').css('top', '10px');

    $('#bot').css('display', 'none');
    close = "false";
  } 

  else if ($(this) && close === "false") {
     console.log('open');
    $('#top').css('transform', 'rotate(0deg)').css('top', '0px');

    $('#mid').css('transform', 'rotate(0deg)').css('top', '10px');

    $('#bot').css('display', 'block');

    close = "true";
  }

});

Firstly close should really be a boolean value to make comparisons easier. However note that you can achieve what you require without the need for that variable at all by simply toggling the a CSS class on the required elements and the display state of #bot . Try this:

#top {
    top: 0;
}
#top.open { 
    transform: rotate(45deg);
    top: 10px;  
}
#mid.open { 
    transform: rotate(-45deg);
    top: 10px; 
}
$(document).on('click', '[data-toggle-nav]', function(event) {
    $('#top, #mid').toggleClass('open');
    $('#bot').toggle();
});

Working example

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