2014-02-20 28 views
2

似乎无法获得不是NaN错误将被替换为0。尝试使用rapply,但不为我工作。无法将NaN替换为0 - 尝试过注射器

window.onload = function() { 
    var first = document.getElementById('firstFieldId'), 
     second = document.getElementById('secondFieldId'), 
     third = document.getElementById('thirdFieldId'), 
     fourth = document.getElementById('fourthFieldId'); 

    first.onkeyup = function() { 
     var value; 

     // Get the value and remove the commas 
     value = first.value.replace(/,/g, ""); 

     // Make it a number 
     value = parseInt(value, 10); 

     // Add one to it 
     ++value; 

     // Turn it back into a string 
     value = String(value); 

     // Put it in the other text box, formatted with commas 
     second.value = numberWithCommas(value); 
    }; 
    third.onkeyup = function() { 
     var value; 

     // Get the value and remove the commas 
     value = third.value.replace(/,/g, ""); 

     // Make it a number 
     value = parseInt(value, 10); 

     // Add one to it 
     ++value; 

     // Turn it back into a string 
     value = String(value); 

     // Put it in the other text box, formatted with commas 
     fourth.value = numberWithCommas(value); 
    }; 

    function numberWithCommas(x) { 
     return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); 
    } 
}; 

发了的jsfiddle http://jsfiddle.net/7r5SF/2/ - 如果你把在第一或第三场一个数字,然后将其清除,第二或第四场将显示为NaN ...它需要说0

任何帮助将是伟大的!

回答

1

更换

++value; 

value = isNaN(value) ? 0 : value+1 

JSFiddle

+0

感谢@马特。虽然我仍然无法在JSFiddle中工作...... – verrucktfuchs

+0

@verrucktfuchs对不起,有'isNan'而不是'isNaN'。这是一个可用的[JSFiddle](http://jsfiddle.net/7r5SF/22/)。 – Matt

+0

非常感谢。奇迹般有效! – verrucktfuchs