使用try catch

时间:2017-04-10 10:21:19

标签: javascript jquery

我有html元素和js代码的html页面。但是如果页面没有.chart我在控制台中有js错误。

所以我使用try-catch。但它似乎并不好。

try{
    $('.chart').easyPieChart({
        animate: 2000,
        barColor: '#333',
        easing: 'easeOutBounce',
        onStep: function (from, to, percent) {
            $(this.el).find('.percent').text(Math.round(percent));
        }
    });
} catch(err) {

}

那么如何修改我的代码?

4 个答案:

答案 0 :(得分:3)

尝试检查元素是否存在而不是使用try..catch:

if ($('.chart').length > 0) {
    $('.chart').easyPieChart({
        animate: 2000,
        barColor: '#333',
        easing: 'easeOutBounce',
        onStep: function (from, to, percent) {
            $(this.el).find('.percent').text(Math.round(percent));
        }
    });
}

答案 1 :(得分:3)

在调用插件之前检查.chart长度。您可以为其他条件添加else。不要为此目的使用try catch。



if ($('.chart').length >0 ) 
{
$('.chart').easyPieChart({
        animate: 2000,
        barColor: '#333',
        easing: 'easeOutBounce',
        onStep: function (from, to, percent) {
            $(this.el).find('.percent').text(Math.round(percent));
        }
    });
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

此测试的try catch功能不足:

if ($('.chart').length > 0 && $('.chart').easyPieChart) //this will test if the chart element is present and easyPieChart is available as a method.
{
  $('.chart').easyPieChart({
      animate: 2000,
      barColor: '#333',
      easing: 'easeOutBounce',
      onStep: function (from, to, percent) {
          $(this.el).find('.percent').text(Math.round(percent));
      }
  });

}

您基本上想要测试对象是否可用。这称为特征检测,简单的if-else就足够了。

这应该检查方法是否存在,如果不存在,你可以使用else来做某事。如果该方法不存在,则返回undefined

此处建议的其他方法使用 jQuery 的内部工作方式。当使用选择器调用jQuery函数$并且未找到时,length属性将为0。表示未找到任何元素。由于该元素不存在,该方法也不存在。

答案 3 :(得分:0)

您的代码似乎没有任何问题。如果图表元素不存在于DOM中,则jQuery将抛出错误。抓住它并将其打印到控制台以查看错误。它可能是一个与jQuery无关的错误。您仍应将其打印到控制台以查看它或使用开发人员工具检查错误变量。

try{
    $('.chart').easyPieChart({
        animate: 2000,
        barColor: '#333',
        easing: 'easeOutBounce',
        onStep: function (from, to, percent) {
            $(this.el).find('.percent').text(Math.round(percent));
        }
    });
} catch(err) {
   console.log(err);
}

另外,在进行jQuery调用之前,请尝试确保DOM已完全加载,即使用ready函数。否则,运行代码时可能不存在图表元素。

$(document).ready(function() {

});