繁体   English   中英

在两个if语句中的两个if语句之间声明时,如何在if语句范围之外使用JavaScript变量?

[英]How to use JavaScript variable outside if-statement scope between two if-statements when it is declared in one of them?

我有一个导航菜单,可以在打开和关闭时进行动画处理。 我使用来自GSAP的动画对象TimelineLite 我只需要在菜单打开后创建它,然后就可以在任何时候使用它。 菜单关闭后,我将删除该变量,因为它没有用。 我想避免在click事件之外将其声明为全局变量。 有没有更好的逻辑方法可以做到这一点?还是我应该坚持声明全局变量?

$('.dropdown-toggle').on('click', function() {

  if ($(this).is('.top-toggler:not(.active)')) { // If main menu dropdown toggler is inactive
    // Declare the animating object
    var navTimeline = new TimelineLite(new TweenLite($(this).next('.toggleable').children(), 0.75, {margin: '0', transform: 'perspective(320px) rotateX(0deg)', boxShadow: 'inset 0px 0px 20px 0px rgba(0,0,0,0)'}));
    $(this).addClass('active'); // Give the button class active
    navTimeline.play(); // Open up the menu using the animation
    return;
  }

  if ($(this).hasClass('active')) { // If it is active
    navTimeline.reverse(); // Reverse the animation to close it
  }

});

您可以使用jQuery的data()方法将对象保存到元素的jQuery数据缓存中。 然后,您可以在需要时将其删除/清空

if ($(this).is('.top-toggler:not(.active)')) {
  var navTimeline = new TimelineLite(...);
  $(this).data("timeline",navTimeline)
  //...
}

if ($(this).hasClass('active')) { 
  var navTimeline = $(this).data("timeline");
  navTimeline.reverse();
  $(this).data("timeline",null);
}

如果您确实只想避免使用全局变量,则可以使用IIFE

(function() {
  var navTimeline;

  $('.dropdown-toggle').on('click', function() {

    if ($(this).is('.top-toggler:not(.active)')) { // If main menu dropdown toggler is inactive
      // DO NOT declare here, declared in the IIFE scope
      navTimeline = new TimelineLite(new TweenLite($(this).next('.toggleable').children(), 0.75, {margin: '0', transform: 'perspective(320px) rotateX(0deg)', boxShadow: 'inset 0px 0px 20px 0px rgba(0,0,0,0)'}));
      $(this).addClass('active'); // Give the button class active
      navTimeline.play(); // Open up the menu using the animation
      return;
    }

    if ($(this).hasClass('active')) { // If it is active
      navTimeline.reverse(); // Reverse the animation to close it
    }

  });
})();  // execute the IIFE

暂无
暂无

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

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