简体   繁体   English

在 Jquery 函数中编写 If 和 If Else 的更好方法

[英]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.首先close应该是一个boolean值,以使比较更容易。 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 .但是请注意,您可以通过简单地切换所需元素上的 CSS 类和#bot的显示状态来#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工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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