JavaScript异常练习:验证输入的数字

验证

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>demo</title>
</head>
<body>
<script>
    function myFunction() {
        try {
            var x = document.getElementById("demo").value;
            if (x == "") throw "值为空";
            if (isNaN(x)) throw "不是数字";
            if (x > 10) throw "太大";
            if (x < 5) throw "太小";
        } catch (err) {
            var y = document.getElementById("mess");
            y.innerHTML = "错误:" + err + "。";
        }
    }
</script>
<h1>验证数字</h1>
<p>
    请输入5到10之间的数字:
</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">测试输入值</button>
<p id="mess"></p>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_22182989/article/details/89228747
今日推荐