javascript - Event handler function out of scope in for -
the handler inside of loop might out of scope , prints "last event added" in console doesn't loop through each element in array. no sure i'm going wrong here, need attaching event listener each .
(function () { if (document.addeventlistener) { this.addevent = function (elem, type, fn) { elem.addeventlistener(type, fn, false); }; } else if (document.attachevent) { this.addevent = function (elem, type, fn) { var bound = function () { return fn.apply(elem, arguments); }; elem.attachevent("on" + type, bound); return bound; }; } if (document.getelementsbyclassname) { this.getclass = function (classname) { return document.getelementsbyclassname(classname); }; } else if (document.queryselectorall) { this.getclass = function (classname) { return document.queryselectorall("." + classname); }; } var elem = getclass("images"), display = getclass("display_box"), rolloverimage = function (e) { console.log("event 'rolloverimage' triggered"); }; console.log(display); console.log(elem); console.log(elem.length); (var = 0; < elem.length; i++) { document.addevent(elem[i], "mouseover", rolloverimage); if (i = elem.length) { console.log("last event added"); } else { console.log("event added " + elem[i]); } }; })();
if wanting addevent function on document object use document.addevent = not this.addevent = putting on global object window
also doesnt loop through of them because assigning i elem array length instead of comparing.
if (i = elem.length) { should be
if (i == elem.length) { because of on first iteration through loop causes i value of elem.length , since i not < elem.length loop exits.
Comments
Post a Comment