源代碼
點擊運行
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>教程</title> </head> <body> <p>請輸出一個 5 到 10 之間的數字:</p> <input id="demo" type="text"> <button type="button" onclick="myFunction()">測試輸入</button> <p id="message"></p> <script> function myFunction() { var message, x; message = document.getElementById("message"); message.innerHTML = ""; x = document.getElementById("demo").value; try { if(x == "") throw "值為空"; if(isNaN(x)) throw "不是數字"; x = Number(x); if(x < 5) throw "太小"; if(x > 10) throw "太大"; } catch(err) { message.innerHTML = "錯誤: " + err; } } </script> </body> </html>
運行結果