0

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);
    }
};

イベントをすべての要素に動的にバインドしようとしていますが、要素をクリックすると、関数が期待どおりに動作しません

4

1 に答える 1

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));
}
于 2013-02-22T14:58:43.887 に答える