<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<p>请输出一个 5 到 10 之间的数字:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">测试输入</button>
<p id="mess"></p>
</body>
</html>
<script type="text/javascript">
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"); // 抓住上面throw抛出的错误,给p标签显示
y.innerHTML="错误:" + err + "。";
}
}
</script>
try使用场景!
猜你喜欢
转载自blog.csdn.net/weixin_43764814/article/details/104335744
今日推荐
周排行