我的选项,以避免在Internet Explorer中的此错误(和document.write)? [英] What are my options to avoid this error (and document.write) in Internet Explorer?
问题描述
我维护的代码中有太多的 document.write
实例。例如,代码将 document.write
一个div,然后使用DOM找到该div,然后附加一个< img> $
I'm maintaining some code that has far too many document.write
instances. For example, the code would document.write
a div, then use the DOM to find that div, then append an <img>
to it.
我试图重构一个相关的部分,看起来更像这样:
I've tried to refactor a relevant piece to look more like this:
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无法打开互联网网站 http://blah.com 。操作中止。
This is throwing an error in IE, saying "Internet Explorer can not open the Internet site http://blah.com. Operation aborted."
我被告知这是因为我需要使用 document.write
。我希望有一个替代,将允许我使用上述方法,而不是强迫我把我的节点变成一个字符串(例如),并通过 document.write
。任何人都可以建议我的问题的解决方案?
I'm told this is because I needed to indeed use document.write
. I'm hoping there's an alternative that would allow me to use the above approach and not force me to turn my node into a string (e.g. "") and append it via document.write
. Can anyone suggest a solution to my problem?
推荐答案
如果这个代码有document.writes,该页面正在加载/解析,不是吗?您应该将代码包装在window.onload事件处理程序中。更好的是,使用jQuery的ready事件,或另一个lib的dom准备好包装。
If this code had document.writes in it, then it was being run while the page was being loaded/parsed, wasn't it? You should wrap your code in a window.onload event handler. Even better, use jQuery's ready event, or another lib's dom ready wrapper.
这篇关于我的选项,以避免在Internet Explorer中的此错误(和document.write)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!