2012-03-02 27 views
0

我想知道如何返回某個索引內特定的子元素被點擊的值。返回JQuery在容器中的特定點擊

通常情況下,默認行爲是使用

var selected = $(this).index(); 

雖然這個工作,因爲它應該,它不會從內部功能,如下列返回索引。

var selected; 

$(container.children()).on('click', function() { 
    selected = $(this).index(); 
    selected.siblings().fadeOut(); 
    selected.animate({ 
     width: 920, 
     height: 440 
    }); 
    selected.fadeOut(); 
}); 

//console.log(selected) = 'undefined'! 

這是什麼和什麼是合適的解決方案?

編輯:

請注意,我已經編輯本作的問題不太具體和本地化,以便其更好地投票。

裏克

回答

1

簡單:

console.log($(this).index()); 
+0

在點擊功能它是正確的。外面它總是-1。如何從INSIDE點擊功能返回您的答案? – 2012-03-02 10:47:02

+0

返回什麼?我不知道你的意思。點擊後,抓住索引,用它做點什麼。這是典型的模式。 – karim79 2012-03-02 10:56:04

+0

在點擊函數之前,我選擇了一個變量var; 在click函數中,我將變量設置爲selected = $(this).index(); 選定的點擊功能爲「未定義」後。 爲什麼不呢? – 2012-03-02 11:31:36