我有一个总和值的表。当我输入不是数字的东西时,我该怎么办,将结果保持为0?
一些代码:
$(document).on('keyup','input',newSum);
function newSum() {
var sum = 0;
var thisRow = $(this).closest('tr');
var total = 0;
$(thisRow).find("td:not(.total) input").each(function () {
sum += parseInt(this.value);
});
// Insertamos el color de la suma de cada fila.
if((sum % 2 == 0)) {$(thisRow).find('.total').animate( { backgroundColor: 'green' }, 1000);}
else{$(thisRow).find('.total').animate( { backgroundColor: 'red' }, 1000);}
$(thisRow).find(".total").html(sum);
$('.total').each(function () {
total += parseInt($(this).html());
});
}
提前谢谢。
答案 0 :(得分:4)
尝试short circuit boolean evaluation:sum += +this.value || 0;
+
尝试将值设置为Number
,如果失败则使用值0
答案 1 :(得分:2)
sum+= isNaN(Number(this.value))?0:Number(this.value);
答案 2 :(得分:1)
停止非数字按键的代码
Js代码:
function checkAlphbet(event) {
var code = event.keyCode ? event.keyCode : event.which;
var currentKey = alphabetKeyRestriction(code, true);
if (!currentKey) {
event.stopPropagation();
} else {
event.preventDefault();
}
}