2010-09-10 53 views
0

有人可以解釋爲什麼下面這個簡單的腳本在Firefox中不起作用,我該如何解決它?當我嘗試打開文件並寫入文件時出現問題

<script type="text/javascript"> 
var w = window.open("a.php"); 
w.document.write("hello"); 
</script> 

感謝很多

+1

你能說「不行」嗎?你期望它做什麼沒有做到? – Jamiec 2010-09-10 09:40:24

+0

@peSHIr。 Javascript中的「open」和「write」不指向file-io。當OP沒有時,不要添加這些 - 這隻會增加混淆。 – 2010-09-10 09:44:14

+0

哎呀,對不起!我不會編輯我基本不知道的東西。沒有真正讀過所有的東西:只有回答有人談論過file-io ..: -/ – peSHIr 2010-09-10 10:11:52

回答

0

我敢肯定使用JavaScript,因爲它是一個客戶端的語言,你不能讀/寫文件?雖然我可能完全錯誤!

編輯:

試試這個代碼:

var new_window, new_window_content = []; 
new_window_content.push('<html><head><title>New Window</title></head>'); 
new_window_content.push('<body>New Window</body>'); 
new_window_content.push('</html>'); 
new_window = window.open("", "", "status,height=200,width=200"); 
new_window.document.write(new_window_content.join('')); 

乾杯,肖恩

+0

嘿,你不讀這裏提的是什麼嗎?在回答之前仔細閱讀問題。 – 2010-09-10 09:34:41

+0

抱歉 - 標題應該沿着「打開一個窗口並向其中寫入內容」的方向。目前在編程論壇上的標題不是這樣。 – seanxe 2010-09-10 09:44:03

0

別人在這裏張貼的答案:他是不是想打開文件和寫入 - 瀏覽器中的javascript是不可能的。他正在嘗試使用w.document.write來做什麼,是在瀏覽器中打開他剛剛打開的網頁的末尾。

谷歌瀏覽器說,這個代碼失敗爲:

>>> var w = window.open("http://www.google.co.uk"); 
undefined 
>>> w.document.write("lol"); 
TypeError: Cannot call method 'write' of undefined 

需要先通過使用document.open()打開文檔流 - 這將在w.document添加write功能:

<script type="text/javascript"> 
var w = window.open("a.php"); 
w.document.open(); 
w.document.write("hello"); 
w.document.close(); 
</script> 
+0

我投下了這個,因爲document.write()函數不是他應該在這裏使用的。請參閱下面Dawn的回答,以獲得更好的方式,即在新頁面中向「DOM元素」添加「hello」。 – 2010-09-10 11:01:34

2

(編輯以使代碼示例顯示更好)

DOM腳本更新,更健壯。

例如

var w = window.open("a.php"); 
w.onload = function(){//you could also use dom ready rather than onload but that is a longer script that I've not included here 
    var body = w.document.getElementsByTagName("body")[0]; 
    body.appendChild(document.createTextNode("bar")); 
} 
+0

這是正確的做法。 – 2010-09-10 11:02:11

相關問題