如何限制输入字段数字在淘汰赛js

问题描述:

我有一个输入字段,我想限制它只用于数值。我怎样才能做到这一点在这里淘汰赛JS如何限制输入字段数字在淘汰赛js

是我的领域

<input data-bind="value: nsc" /> 
+0

利用基因敲除验证 – 2014-08-28 07:01:45

+0

通过@Seminda这里给出的答案比你链接的问题的答案要好得多。 – 2014-08-28 08:50:56

想这问题是已经回答了。 您可能需要创建只接受允许的字符的自定义绑定。

这个问题的答案在此链接后会帮助你:make an input only-numeric type on knockout

+0

@Seminda给出的答案比你链接的问题的答案要好得多。自定义绑定不是理想的解决方案,扩展器更加灵活,并且提供更好的代码分离(您的HTML不应该规定您的领域逻辑,JavaScript应该)。 – 2014-08-28 08:51:55

你可以写在你的视图模型的功能。

ko.extenders.numeric = function(target, precision) { 
//create a writable computed observable to intercept writes to our observable 
var result = ko.pureComputed({ 
    read: target, //always return the original observables value 
    write: function(newValue) { 
     var current = target(), 
      roundingMultiplier = Math.pow(10, precision), 
      newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue), 
      valueToWrite = Math.round(newValueAsNum * roundingMultiplier)/roundingMultiplier; 

     //only write if it changed 
     if (valueToWrite !== current) { 
      target(valueToWrite); 
     } else { 
      //if the rounded value is the same, but a different value was written, force a notification for the current field 
      if (newValue !== current) { 
       target.notifySubscribers(valueToWrite); 
      } 
     } 
    } 
}).extend({ notify: 'always' }); 

//initialize with current value to make sure it is rounded appropriately 
result(target()); 

//return the new computed observable 
return result; 

};

检查此链接如何使用:Sample code

+1

这是迄今为止最好的方法。 (也比链接@ Raghavendra-N发布的接受的答案更好)。这主要是因为两个原因:扩展器比自定义绑定更灵活,并且它促进了更好的代码分离。因此,我的意思是将数字限制在JavaScript中是比较合理的,因为它代表域逻辑,而不是在与呈现相关的HTML中。 – 2014-08-28 08:49:58

+0

嗨汉斯,你能回答这个问题吗?http://*.com/questions/25637663/converting-circular-structure-to-json-in-knockout-js – user2142786 2014-09-03 07:06:21