2012-11-21 37 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"); 
});