2011-08-25 36 views
0

我開始體驗Javascript的神話般的世界,我正在用一個帶有一個javascript函數的html文件製作一個盒子,事實是該警報不會顯示進入文本字段的內容,我做錯了什麼?,這是我的代碼。使用javascript函數的html文件中的錯誤

<html> 
    <head> 
     <script> 
     function showMe() 
     { 
      var nombre= cnombre.value; 
      alert("You are "+ nombre); 
      cnombre.value=""; 
      cnombre.focus(); 
     } 
     </script> 
    </head> 

    <body> 
      Name:<input type ="text" name="cnombre" 
    size="30"> 
      <input type="button" value="Go" 
    onClick=showMe();> 

    </body> 
</html> 

回答

1

更改您的代碼以給文本框一個id,然後通過該id從DOM中檢索文本框。這應該爲你工作:

<html> 
<head> 
    <script> 
    function showMe() { 
    var nombre = document.getElementById('cnombre'); 
    alert("You are " + nombre.value); 
    nombre.value = ""; 
    nombre.focus(); 
} 
    </script> 
</head> 

<body> 
     Name:<input type ="text" id="cnombre" name="cnombre" 
size="30"> 
     <input type="button" value="Go" 
onClick=showMe();> 

</body> 

0

您無法像這樣訪問文本框。根據您的代碼,請參閱http://jsfiddle.net/GUB3E/瞭解有效的示例。

注意id="cnombre"添加到文本框和使用document.getElementById()

相關問題