码迷,mamicode.com
首页 > Web开发 > 详细

JS——try catch throw

时间:2017-10-18 11:51:12      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:error   显示   asc   err   html   class   style   click   innerhtml   

本例检测输入变量的值。如果值是错误的,会抛出一个异常(错误)。catch 会捕捉到这个错误,并显示一段自定义的错误消息:

<script>
function myFunction()
{
try
  {
  var x=document.getElementById("demo").value;
  if(x=="")    throw "empty";
  if(isNaN(x)) throw "not a number";
  if(x>10)     throw "too high";
  if(x<5)      throw "too low";
  }
catch(err)
  {
  var y=document.getElementById("mess");
  y.innerHTML="Error: " + err + ".";
  }
}
</script>

<h1>My First JavaScript</h1>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="mess"></p>

参考:JavaScript 错误 - Throw、Try 和 Catch

JS——try catch throw

标签:error   显示   asc   err   html   class   style   click   innerhtml   

原文地址:http://www.cnblogs.com/wuqiuxue/p/7685829.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!