JavaScript .. Document.write .. странное поведение документа: '( - PullRequest
0 голосов
/ 15 августа 2011

Я получаю очень странное поведение :( Я надеюсь, что кто-то может помочь

Используя запрос 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 Ответ

4 голосов
/ 15 августа 2011

Вот что делает write(), пишет в документе. Если документ уже закрыт (закрыт означает, что он полностью загружен), write () будет перезаписывать документ.

Решение простое: не используйте write (), когда документ уже загружен. Используйте DOM-методы, такие как appendChild () или insertBefore (), для внедрения новых узлов.

...