2

我有以下脚本。当我最初编写它时,它运行良好。然后我加载了页面,它已经损坏并且永久返回NaN。我能够在控制台中成功运行它,但由于某种原因它无法在站点上正常运行。它在 Rails 应用程序内部运行。

$(document).ready(function(){
  $('select').click(function(){
    var often = parseInt($('#biohaz_frequency_often').val());
    var time = parseInt($('#biohaz_frequency_time').val());
    var timeoften = often * time
    if(timeoften == 0){
      var freq = 0;
    }
    else if(timeoften <= 2){
      var freq = 1;
    }
    else if(timeoften <= 4){
      var freq = 3;
    }
    else if(timeoften <= 9){
      var freq = 6;
    }
    else if(timeoften > 9){
      var freq = 10;
    }
    var sever = parseInt($('#biohaz_risk_severity').val());
    var master = parseInt($('#biohaz_risk_mastery').val());
    $('#risk_frequency').html(freq);
    $('#risk_total').html(freq * sever * master);
  })
})
4

2 回答 2

1

运行此诊断:

$(document).ready(function(){
  $('select').click(function(){
    var often = parseInt($('#biohaz_frequency_often').val());
    var time = parseInt($('#biohaz_frequency_time').val());
    var sever = parseInt($('#biohaz_risk_severity').val());
    var master = parseInt($('#biohaz_risk_mastery').val());
    alert([often, time, sever, master].join());
  });
});

这将告诉您四个变量中的哪一个是 NaN。

此外(这可能很重要),$('select').click(...)是相当不寻常的。我希望看到$('select').on('change', ...)。使用click您的 NaN 更有可能是非数字进入计算的结果。如果没有看到 HTML,我无法确定。

最好的策略是确保所有四个选择元素都被初始化(在 HTML 中)并选择了一个有效的选项,然后代码如下:

$(document).ready(function(){
    //cache of static jQuery objects
    var $$ = {
        'often':     $('#biohaz_frequency_often'),
        'time':      $('#biohaz_frequency_time'),
        'sever':     $('#biohaz_risk_severity'),
        'master':    $('#biohaz_risk_mastery'),
        'frequency': $('#risk_frequency'),
        'total':     $('#risk_total')
    };
    $('select').on('change', function(){
        var often = parseInt($$.often.val()),
            time = parseInt($$.time.val()),
            sever = parseInt($$.sever.val()),
            master = parseInt($$.master.val()),
            ot = often * time,//keep this member name short, it's about to be used 4 times in the next line
            freq = (ot == 0) ? 0 : (ot <= 2) ? 1 : (ot <= 4) ? 3 : (ot <= 9) ? 6 : 10;
        $$.frequency.html(freq);
        $$.total.html(freq * sever * master);
    }).trigger('change');//call the handler immediately, with initially selected options
});
于 2012-10-17T21:19:27.760 回答
0

我刚刚根据 benny 的回答和前一秒在这里删除的答案为您整理了一个快速示例 jsfiddle - 它似乎有效:

http://jsfiddle.net/Qr5eF/1/

如果您可以提供自己的 html 来帮助您找到答案。

编辑:更新为新的 jsfiddle,因为我在原版中输入了两个 id。哎呀!

于 2012-10-17T21:09:58.110 回答