Home > Article > Web Front-end > Detailed analysis of JavaScript usage misunderstandings
JavaScript has a lot of code and a lot of rules. For various reasons, we may make unexpected errors in the process of writing code. At such a time, we must learn how to correct these errors. Find them and correct them. JavaScript also has special error-finding codes. These codes will allow us to find errors faster.
1. Error message. If our coding cannot be performed effectively during execution, Java can give a message prompt under specific circumstances to let us know that there is wrong code in this program.
2. Special detection code. There is also a special detection code in Java. This code will detect the program on the web page. If there is an erroneous code, it will be prompted through this detection statement. This is the role of try and catch appearing in pairs in the code.
3. A basic use case of detection code try and catch.
<!DOCTYPE html> <html> <head> <script> var txt=""; function message() { try { acdlert("您好"); } catch(err) { txt="警示有错误代码\n\n"; txt+="这里错了:" + err.message + "\n\n"; txt+="确定继续\n\n"; alert(txt); } } </script> </head> <body> <input type="button" value="你有新的消息" onclick="message()" /> </body> </html>
4.Throw statement. This statement is specifically used to prompt errors. It can also be used to detect the execution results of java functions. It can be used together with the catch statement.
5. A code example of using multiple error detection statements together.
<!DOCTYPE html> <html> <body> <script> function myFunction() { try { var x=document.getElementById("输入").value; if(x=="") throw "不能是空白"; if(isNaN(x)) throw "只能输入数字"; if(x>10) throw "数字太大了"; if(x<5) throw "数字太小了"; } catch(err) { var y=document.getElementById("错误"); y.innerHTML="错在这里:" + err + "。"; } } </script> <h1>这是一个能够检测输入的小程序</h1> <p>数字在5到10之间</p> <input id="输入" type="text"> <button type="button" onclick="myFunction()">请输入数字</button> <p id="错误"></p> </body> </html>
The above is the detailed content of Detailed analysis of JavaScript usage misunderstandings. For more information, please follow other related articles on the PHP Chinese website!