我有以下脚本。当我最初写它时,它完美地工作。然后我加载了页面,它已经破坏并永久地返回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);
})
})
答案 0 :(得分: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
});
答案 1 :(得分:0)
我刚刚根据benny的回答和一秒钟前删除的答案为你准备了一个快速示例jsfiddle - 它似乎有效:
如果你能提供自己的html,可以帮助你找到答案。
编辑:更新到新的jsfiddle,因为我在原版中输错了两个ID。糟糕!