0

我有一些非常奇怪的行为:(我希望有人能帮忙

使用 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 添加的元素,而其他表单元素已经消失了:(

我感谢所有帮助,谢谢。

4

1 回答 1

4

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

解决方案很简单:当文档已经加载时不要使用 write()。使用 appendChild() 或 insertBefore() 等 DOM 方法注入新节点。

于 2011-08-15T02:41:35.377 回答