利用JavaScript在页面中显示猜数字的大小
环境:myeclipse下的web project的html文件下操作
1:代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<script>
function myFunction() {
try {
// 定义一个变量x用来获取值
var x = document.getElementById("demo").value;
if (x == "")
throw "值为空";
if (isNaN(x))
throw "不是数字";
if (x >=9)
throw "太大";
if (x <=7)
throw "太小";
if (x == 8)
document.write("恭喜你猜对了!!!")
//throw "恭喜你猜对了";
}
// 发生错误
catch (err) {
// 发生错误时执行
var y = document.getElementById("mess");
y.innerHTML = "错误:" + err + ".";
}
}
</script>
<h1>利用 JavaScript在页面中猜数字</h1>
<p>请输入 1 到 10 之间的数字:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">请输入测试值</button>
<p id="mess"></p>
</body>
</html>
2:结果