2015-06-11 23 views
-3

發送參數我有這樣的代碼:jQuery的每個:如何與回調

$j(".attribute-option-images").each(closeSelectBox(index,el)); 

然後:

closeSelectBox = function(index,el) 
{ 
    // stuff 
} 

,但我得到的是:

Uncaught ReferenceError: index is not defined 

所以如何將迭代的元素髮送到closeSelectBox

回答

3

在你的第一行,你調用該方法closeSelectBox(),但你希望將它傳遞給each()。 的簽名匹配因此,所有你需要做的是到該行重新寫入:

$j(".attribute-option-images").each(closeSelectBox); 

交出的功能,而不是返回值!

消息「索引未定義」指出,在第一行中,索引實際上未定義,但是它在下面的函數定義中定義。

+0

+1。由於問題的結論是*如何將迭代元素髮送到'closeSelectBox' *,有人可能會指出,這將在迭代器中作爲'this'訪問。 –

1

嘗試

$j(".attribute-option-images").each(function(index, el) { 
    closeSelectBox(index,el) 
}); 

此代碼closeSelectBox(index,el)立即執行的,爲什麼你沒有得到索引錯誤。沒有括號使用像

$j(".attribute-option-images").each(closeSelectBox); 

    function closeSelectBox(index,el){ 

    }