Firefox 在 javascript 中没有捕获“未定义”错误

Firefox not catching "undefined" error in javascript

本文关键字:未定义 错误 javascript Firefox      更新时间:2023-09-26

我有一些javascript代码,它根据SELECT列表中的选定选项调用带有参数的servlet。selectCampaigns(account)中可能没有选项,因此有一个 trycatch .

如果出现以下情况,应调用catch中的代码:

var selectedCampaign = selectCampaigns.options[selectCampaigns.selectedIndex].text;

失败。这在chrome和IE中都有效,但在火狐中它给出了一个TypeErrror

TypeError: selectCampaigns.options[selectCampaigns.selectedIndex] is undefined

这不会触发catch.我可以对如何处理这个问题有一些建议吗?(此外,Firefox 不会显示我插入的任何用于调试的警报(。

function selectcampaign(account) {
    alert('alert1');
    var selectCampaigns = document.getElementById("campaignSelect");
    var urlstrg = "http://localhost:8080/SalesPoliticalMapping/OrgChart";
    try {
        var selectedCampaign = selectCampaigns.options[selectCampaigns.selectedIndex].text;
        urlstrg = "http://localhost:8080/SalesPoliticalMapping/OrgChart?account=" + account +   "&campaign=" + selectedCampaign;
    } catch(err) {
        alert(err);
        urlstrg = "http://localhost:8080/SalesPoliticalMapping/OrgChart?account=" + account;
    } finally {
        window.location.href = urlstrg;
    }
};

您应该更好地测试值,而不是处理错误。

function selectcampaign(account) {
    var selectCampaigns = document.getElementById("campaignSelect");
    var urlstrg = "http://localhost:8080/SalesPoliticalMapping/OrgChart?account=" + account;
    if(selectCampaigns.options[selectCampaigns.selectedIndex]) {
        urlstrg += "&campaign=" + selectCampaigns.options[selectCampaigns.selectedIndex].text;
    }
    window.location.href = urlstrg;
};