3

假设- 假设我有一些 JavaScript 来处理三个不同按钮的点击:

$("#working").click(function () {
    alert("Seth Rollins is the greatest champion of all time.");
    console.log("WWE World Heavyweight Champion");
});

$("#fix-this-error").click(function () {
    alert(this_should_not_show_up_in_the_console);
    console.log("This won't show");
});

$("#should-error").click(function () {
    alert(oipewavqn2389tvb3t8ahwleuhtvab3iwuthabvlewiuweaqhaoiuhva98r3b2);
    console.log("This won't show either");
});

一个将在警告字符串时起作用,并将在警告之后写入的消息记录到控制台。

第二第三个函数将不起作用,因为它们试图警告未定义的变量。他们的后续console.logs不会输出任何东西。

我的问题:是否可以在保持以下属性的同时防止第二个函数的错误输出到控制台?:

  • 一个功能应该按预期工作
  • 第二函数的后续console.log仍然不应该执行
  • 第三函数(和任何其他函数)仍应输出它们的错误

编辑:这是一个可以玩的小提琴 - https://jsfiddle.net/5m40LLmm/2/

超级编辑:我不希望第二个函数中的逻辑执行真正改变。我希望抛出错误,并且.click()处理程序应该在它到达 console.log 之前退出,就像现在一样。我只是想防止显示错误。我不想使用trycatch规避错误,或者在我使用之前以某种方式检查变量是否存在alert()。我知道并希望错误发生,我只是想阻止它的显示。我希望这能更清楚地说明这一点。

4

3 回答 3

2

使用尝试捕获

$("#fix-this-error").click(function () {
    try {
        alert(this_should_not_show_up_in_the_console);
        console.log("This won't show");
    } catch() {}
});

或者在尝试使用之前检查变量是否已定义。

于 2015-07-15T17:04:29.097 回答
2

当你运行它时,console.log 函数永远不会被实际调用。警报功能失败,记录它失败,并且单击侦听器功能退出。console.log()永远达不到。这意味着您只需要阻止警报显示错误。这就是try catch语句有用的地方。

$("#fix-this-error").click(function () {
    try {
        alert(this_should_not_show_up_in_the_console);
        console.log("This won't show");
    } catch (e) {
        // Code jumps here when `alert()` fails.
        // `e` stores information about the error
        // If you don't want to put everything in the try/catch,
        // you can stop the function from continuing execution with
        return;
    }
});
于 2015-07-15T17:16:02.797 回答
0

使用typeof关键字检查是否定义了特定变量。

文档类型

$("#fix-this-error").click(function () {
    if (typeof this_should_not_show_up_in_the_console !== "undefined")
    {
        alert(this_should_not_show_up_in_the_console);
        console.log("This won't show");
    }
});
于 2015-07-15T17:04:53.853 回答