2011-11-06 39 views
3

這可能非常簡單,答案可能非常明顯,但我在此畫空白。Jquery - 將數據傳遞給內聯函數

我有一個綁定.hover()事件的HTML元素數組。我需要知道事件使用了什麼數組索引。

因此,讓我們說元素[7]被盤旋,如何將數字7傳遞給該函數?

這裏是我使用的是什麼:

for (i=0; i<statecount; i++) { 
    $("#"+imagemap[i][0]).hover(function() { 
     // Mouse enters HTML element 

     alert(i); 

     // "i" returns 15, which makes sense because "i" 
     // has changed since this function was defined. 
    }); 
} 

回答

2

使用封閉的包裝來保存狀態。

for (i = 0; i < statecount; i+=1) 
{ 
    (function(i){ 
    $('#'+imagemap[i][0]).hover(function() { 
     alert(i); 
    }); 
    }(i)); 
} 
+0

這個工程,這個小技巧有一個名字嗎?我試圖尋找jquery wrapper,但它顯示wrap()函數等的結果。 謝謝 –

+0

@RadGH:JavaScript自我調用函數我相信...或自調用函數 – JCOC611

+0

「立即調用函數表達式」:http ://benalman.com/news/2010/11/immediately-invoked-function-expression/ – Domenic

1

雖然這不會回答你的問題,你可以得到一個句柄在上空盤旋,利用this函數內部的對象:

for (i=0; i<statecount; i++) { 
    $("#"+imagemap[i][0]).hover(function() { 
     alert(this); 
    } 
} 

您可能需要使用$(this),如果你想JQuery對象。

+0

但這不是他想要的,對吧? – JCOC611

+0

這不是他特別要求的,不,但可能是他想要的。 –

+0

你是對的,它可能:) – JCOC611

0

要小心,因爲這很容易搞砸了:

var hoverer = function(i) { 
    return function() { 
     alert(i); 
    }; 
}; 

for (i=0; i<statecount; i++) { 
     $("#"+imagemap[i][0]).hover(hoverer(i)); 
} 
1

如果您使用> = 1.6的jQuery,$.proxy將咖喱參數:

$.proxy(function(a, b, c) { ... }, this, 'argA', 'argB', 'argC'); 

,所以你可以寫這樣的:

for (i=0; i<statecount; i++) { 
    $("#"+imagemap[i][0]).hover($.proxy(function(index, event) { 
     // Mouse enters HTML element 

     alert(index); 
    }, this, i)); 
} 

請注意,這會將事件推入參數列表的末尾。