在事件侦听器中传递回调参数

时间:2013-02-22 14:48:31

标签: javascript arguments addeventlistener

当我尝试在addEventListener中传递参数时,它表现异常

var animateFunction = function (i) {
if (animBool) {
    Fn.slideData(values(i)); // To fetch some data
    util.animate.tweenAnimate(sliderWrapper, 0 , Math.ceil("-"+sliderWidth));
    animBool = 0;
} else {
    util.animate.tweenAnimate(sliderWrapper, Math.ceil("-"+sliderWidth) ,0);
    animBool = 1;
}
}; 

for (i = 0; i < annotateArray.length; i++) {
//To Remember the state of value "i"
(function (i) {
    //Custom Event Listener for fallback for IE
    util.addEvent(annotateArray[i], "click", animateFunction(i), true);
}(i));
}

 for (i = 0; i < annotateArray.length; i++) {

    //Custom Remove Event Listener for fallback for IE
    util.removeEvent(annotateArray[i], "click", animateFunction);

}

//Custom Bind Event Method
util.addEvent = function (obj, evt, callback, capture) {
    if (window.attachEvent) {
        obj.attachEvent("on" + evt, callback);
    } else {
        if (!capture) {
            capture = false;
        }
        obj.addEventListener(evt, callback, capture);
    }
};

我正在尝试将事件动态绑定到所有元素,但是我点击了该函数未按预期运行的元素

1 个答案:

答案 0 :(得分:1)

您实际上是将undefined作为事件处理程序传递,而不是实际的回调。这里:

util.addEvent(annotateArray[i], "click", animateFunction(i), true);

您正在调用该函数,该函数返回undefined。您必须将函数引用传递给addEventListener。你已经在循环中有了“要记住'i'的价值状态”,但是你没有正确使用它。它应该是:

for (i = 0; i < annotateArray.length; i++) {
    //To Remember the state of value "i"
    (function (i) {
        // Custom Event Listener for fallback for IE
        util.addEvent(annotateArray[i], "click", function() {animateFunction(i)}, true);
    }(i));
}