我在JSFiddle上,由于某种原因,仅当JS代码位于HTML选项卡中的标记中时,才会显示try-catch错误消息,但是当它位于单独的JS选项卡中时,将不会显示try-catch错误。
这将工作:
<!DOCTYPE html>
<html>
<body>
<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="p01"></p>
<script>
function myFunction() {
var message, x;
message = document.getElementById("p01");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}
</script>
</body>
</html>
但这不是:
https://jsfiddle.net/k0rrupt3d/rqejvzoc/
最佳答案
似乎小提琴上的JS部分是局部作用域的。如果将函数声明更改为window.myFunction = function() {
以使其全局,则它将按预期运行。
关于javascript - 为什么我的try catch错误没有出现?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54011979/