2011-08-15 43 views
0

我發現了一些很怪異的行爲:(我希望有人能幫助的JavaScript文件撰寫.. ..奇怪的文件的行爲:「(

使用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

這就是write()正在做什麼,它寫在一個文件裏面。如果文件已經關閉(關閉意味着完全加載),則寫入()將覆蓋文件

解決方法很簡單:當文檔已經加載時,不要使用write()。使用像appendChild()或insertBefore()這樣的DOM方法來注入新節點。