Javascript alternative for this (IE)
I have something lik开发者_C百科e the following code:
for(var i=0;i<4;i++) {
frm = document.createElement("iframe");
frm.width = "100";
frm.height = "100";
frm.src = "source.php";
frm.id = "something";
frm.attachEvent("load", function() { alert(this.id); //Here I need alternative for this.id });
var frameDiv = document.getElementById("frameDiv");
frameDiv.appendChild(frm);
}
It's simplified, but basicly it creates four iframes inside some div and I need to fire some actions based on the id of each frame, when it's completely loaded. It works well, but the problem is in IE. IE doesn't know operator this, so I can't access to the id of frame inside. Is there any alternative which I can use for IE?
Thanks for any help!
Abhijit: Actually, the whole code is like this:
if(frm.addEventListener) {
frm.addEventListener("load", function() { alert(this.id); },false);
}
else if(frm.attachEvent) {
frm.attachEvent("onload", function() { alert(this.id); });
}
else {
frm.onload=function() { alert(this.id); };
}
So it should works in all browsers.
I'm not sure why this wouldn't work in IE, but changing
frm.attachEvent("load", function() { alert(this.id); });
to
// wrap in an anonymous function to fix scope issues
(function(frm) {
frm.attachEvent("load", function() { alert(frm.id); });
})(frm);
should give you a consistent reference to the iframe.
(Edit: Updated above code to fix scope issues within the loop. This is exactly why you should generally avoid creating closures in a loop like this - all frm
references will point to the last defined iframe unless you take explicit measures to fix the scope.)
frm.attachEvent("load", function() { alert(this.id); });
, this should be frm.attachEvent("onload", function() { alert(this.id); });
. In IE you can get the element as event.srcElement. So your code could be frm.attachEvent("onload", function(event) { alert(event.srcElement.id); });
精彩评论