当在其中一个if语句中声明时,如何在两个if语句之间的if语句范围外使用JavaScript变量?
我有一个导航菜单,可以在打开和关闭时设置动画。我使用GSAP中的动画对象当在其中一个if语句中声明时,如何在两个if语句之间的if语句范围外使用JavaScript变量?,javascript,javascript-objects,Javascript,Javascript Objects,我有一个导航菜单,可以在打开和关闭时设置动画。我使用GSAP中的动画对象TimeLineSite。我只需要在菜单打开后创建它,然后我就可以随时使用它。一旦菜单关闭,我将删除变量,因为它是无用的。我希望避免在click事件之外将其声明为全局变量。有没有更好的逻辑方法来实现这一点,或者我应该坚持声明一个全局变量 $('.dropdown-toggle').on('click', function() { if ($(this).is('.top-toggler:not(.active)'))
TimeLineSite
。我只需要在菜单打开后创建它,然后我就可以随时使用它。一旦菜单关闭,我将删除变量,因为它是无用的。我希望避免在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的方法将对象保存到元素的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);
}
如果您真的只想避免使用全局变量,可以使用:
不,您必须在单击处理程序的范围之外定义它。在内部声明的任何变量都只存在于该函数中。你可以把它放在一个全局名称空间或其他地方,但它必须存在于点击处理程序之外。太好了,我从来都不知道这一点。使用这种方法有什么后果吗?我可以一直使用它吗?或者我需要先了解一些关于它的知识吗?没有我知道的后果。只要有与数据关联的DOM元素,就可以始终使用它。使用
$(element).data()
或。访问链接的文档页面了解更多信息
(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