2011-09-13 125 views
4

我打開一個彈出窗口,使用popup = window.open(....),然後嘗試在彈出窗口中插入一些html到div中。更改彈出窗口內容

popup.document.getElementById('div-content').innerHTML = "hello world";不做任何事情,但是,popup.document.getElementById('the-field').value = "Hello There";更改字段的內容與id =「the-field」。

任何想法爲什麼一個工作,但不是另一個?我如何更換div的內容?

希望你能幫助。

編輯: 彈出

<!DOCTYPE html> 
<html> 
    <head> 
     <title>Report</title> 
     <meta charset="utf-8"> 
    </head> 

    <body> 
     <header> 

     </header> 

     <div id="div-content"></div> 

     <div id="report-container"> 
      <input type="text" id="the-field" name="the_field"/> 
     </div> 

     <footer> 
     </footer> 

    </body> 

</html> 

代碼

function reportComplete(report_content) 
    { 
    var popup; 
    var template_path; 

    template_path = base_url + "application/views/secure/reports_preview.php"; 
    popup = window.open(template_path, "Report", "scrollbars=yes ,resizable=yes"); 

    popup.document.getElementById('the-field').value = "Hello There"; // this works 

    popup.document.getElementById('div-content').innerHTML = "hello world"; 

    } 
+1

您可以將代碼發佈在主機頁面和彈出窗口中嗎? –

+0

我編輯了主題並添加了代碼。謝謝 – djeetee

回答

3

我覺得這裏的問題是,當你嘗試在彈出窗口中的文件尚未加載完畢訪問它的一部分。在我的機器上,所有的div都不能通過提供的代碼進行訪問。

如果要插入的內容是固定的,那麼只需在彈出頁面上進行所有這些更改,以便只有在文檔完全加載時才能使其發生。如果您需要發送一些動態內容,最簡單的方法可能是使用查詢字符串。

更新: 只有當彈出窗口完成加載後,纔有辦法觸發DOM操作函數。首先,你需要在主窗口的回調函數,並把所有的DOM操作代碼有:

window.callback = function(doc) { 
    doc.getElementById('the-field').value = "Hello there"; 
    doc.getElementById('div-content').innerHTML = "Hello world"; 
} 

然後,只需綁定一個函數調用彈出窗口對身體onload事件:

<script type="text/javascript"> 
    function loaded() { 
     window.opener.callback(document); 
    } 
</script> 
<body onload="loaded();"><!-- body content --></body> 
+0

你是對的!這是一個計時問題。如果我在'popup.document.getElementById('the-field')。value =「Hello There」上設置了一個斷點,那麼兩個調用都會成功。 div和字段是可更新的。現在的問題是如何知道彈出窗口何時可以被操縱? – djeetee

+0

我已經更新了答案。希望有所幫助。 – nfang

+0

不錯!感謝您發佈代碼。非常感謝。 – djeetee

5

...或簡單地說:

<script type="text/javascript">  
function reportComplete(report_content) 
{ 
    var popup; 
    var template_path; 

    template_path = base_url + "application/views/secure/reports_preview.php"; 
    popup = window.open(template_path, "Report", "scrollbars=yes,resizable=yes"); 

    popup.window.onload = function() { 
     popup.document.getElementById('the-field').value = "Hello There"; 
     popup.document.getElementById('div-content').innerHTML = "hello world"; 
    } 
} 
</script>