[英]In Firebase's Realtime Database, how can I pass my own arguments to an event listener's callback?
[英]Pass Arguments for Callback in Event Listener
當我嘗試在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);
}
};
我正在嘗試將事件動態綁定到所有元素,但是我單擊該元素時,該函數的行為不符合預期
您實際上將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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.