一、直接启用浏览器调试功能
Chrome浏览器中:
1.按下F12打开调试界面。
2.选择source选项卡,选中script文件打开。
3.单击行增删断点,F10单步调试,F11进入函数,F8下一个断点, 鼠标移动到变量上可以查看该变量的值。
4. 右边窗口的callStack可以看到调用栈;watch Expressions可以添加监视值,scope Variables可以看到当前区域变量的值等。
5.F12关闭调试功能。
二、输出Log,使用console.log,对于比较复杂的逻辑很有效
实例函数,逻辑中输出:
<script>function testClick(){
var testInput=AZJ.getElementsByClassName("testme-","input");
//由于这里是两个参数,所以用for语句遍历两个参数,分别显示出来
for(var i=0;i<testInput.length;i++){
console.log("The index :%d, value: %s", i, testInput[i].value);
alert(testInput[i].value);
}
}
</script>
对JS错误输出Log:
<script>
onerror = handleErr; // 错误的调试
function handleErr(msg,url,l)}
</script>
三、try catch预防错误,否则错误发生后面的语句没有得到执行。
1.直接用catch(error)中的error字符串信息。
<!DOCTYPE html>
<html>
<head>
<script>
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()">
</body>
</html>
2.try中thow字符串,catch(error)中的得到throw的字符串。
<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>