我正在尝试找到一种方法来最小化 Selector 查找的数量。我的问题是我有一个用基本 $(document).ready() 定义的变量,需要在嵌套在 $(document).ready() 内的函数内更新
考虑这个例子(编辑:我更新它以更具解释性)
<script>
//var $current_page = $home_page; **<--I DONT want to do this, going global
and of course it doesn't work since
$home_page isn't defined yet.**
$(document).ready(function() {
var $home_page = $("#home-page");
var $portfolio_page = $("#portfolio-page");
var $about_page = $("#about-page");
var $current_page = $home_page; // **<--This variable, in this scope level,
// is what I want updated**
$("#home-btn").click(function () {
$current_page.stop()
$current_page.show()
$current_page.animate({
duration: 360,
easing: 'easeInCirc',
complete: function() {
$(this).css({ top: -700 });
}
);
$current_page = $home_page;
});
$("#portfolio-btn").click(function () {
$current_page.stop()
$current_page.show()
$current_page.animate({
duration: 360,
easing: 'easeInCirc',
complete: function() {
$(this).css({ top: -700 });
}
);
$current_page = $portfolio_page; //<--This needs to somehow update the
// variable in the $(document).ready
// scope, but not global**
});
});
<script>
如何更新变量 $current_page而不使其成为全局变量?
编辑:这样做是为了在您单击菜单项时为当前页面 div 设置动画。是的,它缺少一些东西,是的,它可能没有意义。这只是一个例子,而不是实际的应用程序。
我知道这个例子对性能来说仍然微不足道,忽略这个事实。我只想知道如何做到这一点,而不是关于它是最佳实践还是性能的教训。多谢你们。