Jquery each:如何使用回调发送参数

时间:2015-06-11 11:14:41

标签: jquery

我有这段代码:

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

然后:

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

但我得到的只是:

Uncaught ReferenceError: index is not defined

那么如何将迭代元素发送到closeSelectBox

2 个答案:

答案 0 :(得分:3)

在第一行中,您调用方法closeSelectBox(),但您希望将其传递给each()。 签名是匹配的,因此您需要做的就是将该行重写为:

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

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

消息"索引未定义" state,在第一行中,index实际上没有定义,但它在下面的函数定义中定义。

答案 1 :(得分: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){ 

  }
相关问题