我試圖添加一個模糊事件到一些表單元素,它會爲我運行一些代碼。在最初的模糊之後,我試圖從該元素中刪除偵聽器,以便它不會再次觸發。添加addEventListener後似乎無法removeEventListener
onblur事件工作正常,但由於某種原因eventListener.remove似乎從未觸發,所以模糊不會被刪除。任何想法,我做錯了什麼?
基於lincolnk的意見更新,但仍然不是在IE工作:
(function() {
var els = [document.getElementsByTagName('input'),
document.getElementsByTagName('select')],
eventListener = {
add: function(el, ev, fn) {
if (window.addEventListener) { // Standard
el.addEventListener(ev, fn, false);
} else if (window.attachEvent) { // IE
var iefn = function() { fn.call(el) };
el.attachEvent('on' + ev, iefn)
} else { return false };
},
remove: function(el, ev, fn) {
if (window.removeEventListener) { // Standard
el.removeEventListener(ev, fn, false)
} else if (window.detachEvent) { // IE
var iefn = function() { fn.call(el) };
el.detachEvent('on' + ev, iefn)
} else { return false };
}
},
wtFormTracker = function() {
console.log(this.name);
eventListener.remove(this, 'blur', wtFormTracker);
};
for (var i = 0, j = els.length; i < j; i++) {
for (var y = 0, z = els[i].length; y < z; y++) {
eventListener.add(els[i][y], 'blur', wtFormTracker);
}
}
})();
UPDATE:在所有瀏覽器
(function() {
var els = [document.getElementsByTagName('input'),
document.getElementsByTagName('select')],
eventListener = {
add: function(el, ev, fn) {
if (window.addEventListener) { // Standard
el.addEventListener(ev, fn, false);
} else if (window.attachEvent) { // IE
el.attachEvent('on' + ev, fn)
} else { return false };
},
remove: function(el, ev, fn) {
if (window.removeEventListener) { // Standard
el.removeEventListener(ev, fn, false)
} else if (window.detachEvent) { // IE
el.detachEvent('on' + ev, fn)
} else { return false };
}
},
wtFormTracker = function(el) {
var target = el.target || el.srcElement;
console.log("'WT.ti','title-of-page','WT.ac', " + target.name);
eventListener.remove(target, 'blur', wtFormTracker);
};
for (var i = 0, j = els.length; i < j; i++) {
for (var y = 0, z = els[i].length; y < z; y++) {
eventListener.add(els[i][y], 'blur', wtFormTracker);
}
}
})();
我發佈了更新的代碼...這是你指的IE? – CoryDorning 2010-10-20 02:42:20
@CoryDorning看起來不錯。 – lincolnk 2010-10-20 05:14:06