[英]Javascript - Nothing happens when I click this button connected to a function
因此,我正在嘗試驗證輸入字段,其中輸入字段不能為空。 如果有人沒有在輸入字段中輸入任何文本,然后單擊“開始新游戲”按鈕,它將顯示一條警告消息,提示您需要輸入名稱。
但是,由於某些原因,我的代碼未顯示警報消息。
這是我的代碼。
<html> <head> <title>Tic Tac Toe</title> </head> <script> function myFunction() { if (document.getElementById(“playerNameNew").innerHTML == null) { alert("Name must be filled out"); return false; } } </script> <body> <header> <h1>Tic - Tac - Toe</h1> </header> <h3>Start a new Game</h3> <input type="text" id="playerNameNew" placeholder="Enter your name" required> <button onclick="myFunction()" id="new">Start a New Game</button> </body> </html>
getElementById
是一個對象,但是,您真正想要的是按照getElementById(...)
調用該函數。 .innerHTML
返回HTML而不是輸入的值。 .trim()
函數)。 建議:使用函數.addEventListener()
綁定click事件。
<html> <head> <title>Tic Tac Toe</title> </head> <script> function myFunction() { if (!document.getElementById("playerNameNew").value.trim()) { alert("Name must be filled out"); return false; } } </script> <body> <header> <h1>Tic - Tac - Toe</h1> </header> <h3>Start a new Game</h3> <input type="text" id="playerNameNew" placeholder="Enter your name" required> <button onclick="myFunction()" id="new">Start a New Game</button> </body> </html>
if (document.getElementById("playerNameNew").value == '') {
alert("Name must be filled out");
return false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.