我在 JSFiddle 上,出于某种原因,try-catch 错误消息仅在 JS 代码位于 HTML 选项卡中的标记内时显示,但当它位于单独的 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>
最佳答案
fiddle 上的 JS 部分似乎是局部范围的。如果您将函数声明更改为 window.myFunction = function() {
以使其成为全局函数,它将按预期运行。
关于javascript - 为什么我的 try catch 错误没有出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54011979/