我正在维护一些包含太多 document.write
的代码实例。例如,代码将 document.write
一个 div,然后使用 DOM 找到那个 div,然后附加一个 <img>
我试图重构一个相关的部分,使其看起来更像这样:
var node_to_append = document.createElement("div");
//node_name is a hardcoded constant
node_to_append.id = node_name;
var i = 0;
for( i = 0; i < request_urls.length; i++) {
var image_to_append = document.createElement( "img" );
image_to_append.width = 1;
image_to_append.height = 1;
image_to_append.alt = "";
image_to_append.src = request_urls[ i ];
node_to_append.appendChild( image_to_append );
}
//finally, append the div to the HTML doc
document.body.appendChild( node_to_append );
这会在 IE 中引发错误,显示“Internet Explorer 无法打开 Internet 站点 http://blah.com。操作已中止。”
有人告诉我这是因为我确实需要使用 document.write
.我希望有一种替代方法可以让我使用上述方法,而不是强制我将我的节点变成一个字符串(例如“”)并通过 document.write
附加它。 .任何人都可以建议解决我的问题吗?
最佳答案
如果此代码中包含 document.writes,那么它会在页面加载/解析时运行,不是吗?您应该将代码包装在 window.onload 事件处理程序中。更好的是,使用 jQuery 的就绪事件,或另一个库的 dom 就绪包装器。
关于javascript - 在 Internet Explorer 中避免此错误(和 document.write)的选项有哪些?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6283875/