JavaScript.. Document.write.. weird document behaviour:'(

送分小仙女□ 提交于 2021-02-05 11:59:47

问题


I'm getting some very weird behaviour:( i hope someone can help

Using xmlhttp request im getting a javascript file with document. write and it looks something like this:

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

I basically want to add those input elements in a form which is inside an 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);

Now when i try to get doc.getElementsByTagName('input'); i only get the elements that were added from the document.write and he other form elements have disappeared :(

I appreciate all help, thanks.


回答1:


That's what write() is doing, it writes inside a document. If the document is already closed(closed means completely loaded), write() will overwrite the document.

Solution is simple: don't use write() when the document is already loaded. Use DOM-methods like appendChild() or insertBefore() to inject new nodes.



来源:https://stackoverflow.com/questions/7061215/javascript-document-write-weird-document-behaviour

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