Javascript 替代方案(IE)
我有类似下面的代码:
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);
}
它被简化了,但基本上它在某个 div 内创建了四个 iframe,当它完全加载时,我需要根据每个框架的 id 触发一些操作。效果很好,但问题出在 IE 上。 IE不知道这个运算符,所以我无法访问内部框架的id。有没有可以用于 IE 的替代方案?
感谢您的帮助!
Abhijit:实际上,整个代码是这样的:
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); };
}
所以它应该适用于所有浏览器。
I have something like 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定为什么这在 IE 中不起作用,但更改
为
应该可以为您提供对 iframe 的一致引用。
(编辑:更新了上面的代码以修复循环内的范围问题。这正是您通常应该避免在这样的循环中创建闭包的原因 - 所有
frm
引用都将指向最后定义的 iframe,除非您采取明确的措施来修复范围。)I'm not sure why this wouldn't work in IE, but changing
to
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); });
,这应该是frm.attachEvent("onload", function() {alert(这个.id); });
。在 IE 中,您可以通过 event.srcElement 获取该元素。所以你的代码可以是frm.attachEvent("onload", function(event) {alert(event.srcElement.id); });
frm.attachEvent("load", function() { alert(this.id); });
, this should befrm.attachEvent("onload", function() { alert(this.id); });
. In IE you can get the element as event.srcElement. So your code could befrm.attachEvent("onload", function(event) { alert(event.srcElement.id); });