What are my options to avoid this error (and document.write) in Internet Explorer?

99封情书 提交于 2019-12-24 10:04:30

问题


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 );

This is throwing an error in IE, saying "Internet Explorer can not open the Internet site http://blah.com. Operation aborted."

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?


回答1:


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.



来源:https://stackoverflow.com/questions/6283875/what-are-my-options-to-avoid-this-error-and-document-write-in-internet-explore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!