2010-04-23 26 views
2

我已經打開了新的窗口使用JavaScript:如何將JavaScript寫入單獨的窗口?

var newwin = window.open('','preview','width=600,height=500'); 

現在我想一些JavaScript寫的窗口:

newwin.document.write("<script type='text/javascript'>alert('Hi!');<" + "/script>"); 
newwin.document.close(); 

然而,該腳本永遠不會被執行。難道我做錯了什麼?


更新:好吧,現在我得到了它的一部分工作。下面是當前代碼我有:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head> 
<script type='text/javascript'> 

function SetContent() 
{ 
    $('#content').html('New Text'); 
} 

function dowin() 
{ 
    var newwin = window.open('','preview','width=600,height=500'); 

    newwin.document.write('<div id="content"></div><b>This should be replaced...</b>'); 
    newwin.document.close(); 

    var script = newwin.document.createElement("script"); 
    script.type = "text/javascript"; 
    script.src = 'jquery.js'; 
    newwin.document.body.appendChild(script); 

    var script2 = newwin.document.createElement("script"); 
    script2.type = "text/javascript"; 
    script2.textContent = "(" + SetContent + ")();"; 
    newwin.document.body.appendChild(script2); 
} 

</script> 
</head> 
<body> 
<button onclick='dowin();'>Open</button> 
</body> 
</html> 

它應該改變div的內容,但你可以看到,它沒有。

+0

其實,你的代碼在我的Firefox 3.7 btw上運行良好,但你也可以嘗試我的方法。 – YOU 2010-04-23 06:53:05

+0

順便說一句,Chrome的檢查器是無用的,因爲它被禁用彈出窗口:( – 2010-04-23 21:27:42

回答

1

您的代碼在我的Firefox 3.7,Opera 10和IE6上運行正常,但您可以使用DOM功能嘗試不同的方法。

var newwin = window.open('','preview','width=600,height=500'); 

function sayHi(){ 
    alert('Hi!'); 
} 

var script = newwin.document.createElement("script"); 
script.type = "text/javascript"; 
script.textContent = "(" + sayHi + ")();"; 
newwin.document.body.appendChild(script); 

如果它不工作,你應該仔細檢查彈出窗口攔截器或JavaScript阻滯劑瀏覽器。

+0

如果我想在新窗口中引用外部.js文件怎麼辦? – 2010-04-23 06:55:37

+1

@George,試一下'script.src ='http://external.com/some.js''而不是'.textContent' – YOU 2010-04-23 06:58:05

+0

'textContent'在IE中不起作用... – James 2010-04-23 07:18:29

0
function SetContent() 
{ 
    $(newwin).find('#content').html('New Text'); 
} 
+0

這是行不通的。 – 2010-04-23 22:15:20

+0

好的,可能是: $(newwin.document).find('#content')。html('New Text'); – David 2010-04-23 22:20:55