2009-02-22 39 views
4

我剛開始學習JavaScript,想知道爲什麼這個簡單的代碼片段在我點擊「調用函數」按鈕時會掛起。我錯過了什麼?新手:掛在功能調用瀏覽器

<html> 
<head> 

<script type="text/javascript"> 
function myfunction() 
{ 
document.write("hello"); 
} 
</script> 

</head> 
<body> 

<form> 
<input type="button" 
onclick="myfunction()" 
value="Call function"> 
</form> 

</body> 
</html> 
+0

「hangs」是什麼意思? – Canavar 2009-02-22 16:57:04

+0

當我點擊「通話功能」按鈕時,我的Firefox標籤會無限期地顯示一個「頁面加載」圖標。 – RexE 2009-02-22 17:39:41

回答

3

您需要的元素中寫入或給出一個元素的值,或者你應該使用文檔寫這樣的:

<html> 
<head> 

<script type="text/javascript"> 
function myfunction() 
{ 
document.getElementById("lblMessage").innerText = "hello"; 
document.getElementById("txtMessage").value = "hello"; 
//document.write("hello"); 
} 
</script> 

</head> 
<body> 

<form> 

<script type="text/javascript"> 
document.write("This is written while page processed by browser !<br />"); 
</script> 

<input type="text" id="txtMessage" /><br /> 
<span id="lblMessage"></span><br /> 
<input type="button" 
onclick="myfunction()" 
value="Call function"> 
</form> 

</body> 
</html> 
1

您希望函數輸出其「hello」的位置?進入按鈕的源代碼?這是沒有意義的。瀏覽器很混亂並且掛起。

Document.write不會奇蹟般地在文檔的末尾插入某些內容。它把它的東西寫在那裏,它被稱爲。

+0

你錯了。當一個文件被解析時,document.write可以用來插入內容。解析文檔關閉後。如果在文檔關閉後使用document.write,則會創建一個新文檔並替換原始文檔。瀏覽器不會混淆也不會掛起。 – some 2009-02-22 19:08:23

3

如果你只是想看看你的按鈕做的事情,然後嘗試:

alert("Hello"); 

,而不是文件撰寫。

1

不太清楚你所說的「掛」的意思......嘗試了這一點...可以刪除警報,但會告訴你它正在執行的位置...

<html> 
    <head> 
    <script type="text/javascript"> 
     function myFunction() { 
      //for debugging 
      alert('Made it into function'); 
      document.getElementById('MyOutputDiv').innerHTML = 'Word To Your Mom...'; 
      //for debugging 
      alert('function complete'); 
     } 
    </script> 
    </head> 
    <body> 
    <input type='button' onclick='myFunction();' value='Call Function'> 
    <br> 
    <div id='MyOutputDiv'></div> 
    </body> 
</html> 
0

document.write,但是在哪裏?你必須指定這個。

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title>Hello</title> 
</head> 
<body> 
<pre><script type="text/javascript"> 
function myfunction() { 
    d = document.getElementById('hello'); 
    d.style.display = "block"; 
    d = document.getElementById('callme'); 
    d.style.display = "none"; 
} 
</script> 
</pre> 
<div id="hello" style="display:none"> 
Hello 
</div> 
<div id="callme"> 
    <input type="button" 
    onclick="myfunction()" 
    value="Call function"> 
    </input> 
</div> 
</body> 
</html>