2012-11-21 36 views
0

有人能告诉我为什么在第一个alert(items.index($(this))) = 1和第二个alert(items.index($(this))) = -1。这个值在另一个函数中如何改变?功能中丢失变量

$(function() { 
var items = $('#v-nav>ul>li').each(function() { 
    $(this).click(function() { 
     //remove previous class and add it to clicked tab 
     items.removeClass('current'); 
     $(this).addClass('current'); 

     alert(items.index($(this))); 

     $('#v-nav>div.tab-content').fadeOut("slow", function() { 
     alert(items.index($(this))); 
     $('#v-nav>div.tab-content').eq(items.index($(this))).fadeIn("slow"); 
     }); 


     // window.location.hash = $(this).attr('tab'); 
    }); 
}); 
+0

就目前来看,我没有在问题中看到一个'return'语句。你有别的东西要透露给我们吗? – 2012-11-21 20:06:14

+0

它会出现你的items变量不会填充,直到你的每个函数完成后。尽管我没有看到代码就看不出来。 –

+0

我已经重新说明了这个问题。这可能会使我看到的行为更加清晰。 – everreadyeddy

回答

3

this指当前对象。

在第一个版本,

this$('#v-nav>ul>li')列表的一个项目。

而在第二个版本,

this$('#v-nav>div.tab-content')


选择。如果您想保留的this以前的值,然后在变量进行缓存DOM对象。 (高速缓存$(this)是一个非常好的做法,因为你总是保存一个函数调用)。

当您使用$(this)时,您实际上将this传递到$函数。

$(function() { 
var items = $('#v-nav>ul>li').each(function() { 
    var $this = $(this); 
    $this.click(function() { 
     //remove previous class and add it to clicked tab 
     items.removeClass('current'); 
     $this.addClass('current'); 

     alert(items.index($this)); 

     $('#v-nav>div.tab-content').fadeOut("slow", function() { 
     alert(items.index($this)); 
     $('#v-nav>div.tab-content').eq(items.index($(this))).fadeIn("slow"); 
     }); 


     // window.location.hash = $(this).attr('tab'); 
    }); 
}); 
0

你必须考虑每个“this”的上下文,每个回调都有一个独特的“this”变量。如果你想保持原来的这个局面,这样做:

var self = this; 
1

里面动画的回调函数,this不是你点击,它被动画的元素的元素。

“该回调没有发送任何参数,但是这被设置为DOM 被动画的元素。”

http://api.jquery.com/fadeOut/

(如果它没有被设置为动画元素,它会一直到window对象的引用。)

复制动画以外的参照​​可变电话:

var t = this; 
$('#v-nav>div.tab-content').fadeOut("slow", function() { 
    alert(items.index($(t))); 
    $('#v-nav>div.tab-content').eq(items.index($(t))).fadeIn("slow"); 
});