JavaScript .. Document.write ..奇怪的文档行为:'(

时间:2011-08-15 02:33:04

标签: javascript document.write

我得到一些非常奇怪的行为:(我希望有人可以提供帮助

使用xmlhttp请求获取带文档的javascript文件。写,它看起来像这样:

document.write("<input type='hidden' name='orange' value='17' />");
document.write("<input type='hidden' name='apple' value='29' />"); 

我基本上想要在iframe内部的表单中添加这些输入元素。

// i get the document of the iframe
var docc = doc.getElementById("rs-iframe").contentDocument;
var body = docc.getElementsByTagName('body')[0];

// i put the response from xmlhttprequest in a script tag
var script = docc.createElement('script');
script.type = "text/javascript"; 
script.text = "//<![CDATA["+xmlhttp.responseText+"//]]>";

// i get the position where i want to put my script tag
var elem = form.getElementsByTagName('script')[6];  

// i try to insert my script tag from xmlhttprequest before the script i retrieve from the form
elem.parentNode.insertBefore(script, elem);

// the i append the form to the body of the iframe document                      
body.appendChild(form);

现在,当我尝试获取doc.getElementsByTagName('input');时,我只获取了从document.write中添加的元素,并且其他表单元素已经消失:(

感谢所有人的帮助,谢谢。

1 个答案:

答案 0 :(得分:4)

这就是write()正在做的事情,它写在文档中。如果文档已经关闭(关闭意味着完全加载),write()将覆盖文档。

解决方案很简单:在文档加载时不要使用write()。使用像appendChild()或insertBefore()这样的DOM方法来注入新节点。

相关问题