【问题标题】:Knockout.js - Forcing input to be numeric - allow dot and comma notationKnockout.js - 强制输入为数字 - 允许点和逗号表示法
【发布时间】:2012-11-16 12:58:45
【问题描述】:

为了更好地理解,请转到http://knockoutjs.com/documentation/extenders.html 并查看实时示例 1:强制输入为数字

我可以用 . (点)但不带逗号。然后金额跳到0。

知道如何允许点和逗号吗?我想允许输入像 20.00 和 20,00

亲切的问候,

K.

【问题讨论】:

    标签: knockout-2.0 knockout-validation


    【解决方案1】:

    您可能不仅希望接受带逗号的数字字段,还希望使用逗号从您的 VM 输出数字作为小数点。因此,您还需要实现底层计算 observable 的 read getter 函数。如果您不关心舍入,还可以简化 write 函数。完整代码如下:

    ko.extenders.numeric = function(target) {
        var result = ko.computed({
            read: function() {
                var value = target();
                return isNaN(value) || value===null || value===''
                    ? value
                    : value.toString().replace('.',',');
            }
            ,write: function(newValue) {
                if (typeof newValue === "string") {
                    newValue = newValue.replace(",", ".");
                }
                if (newValue !== target()) {
                    target(newValue);
                }
            }
        });
        result(target());
        return result;
    };  
    

    【讨论】:

      【解决方案2】:

      您可以在数字扩展器中实现一个小修复(参考您发布的扩展器文档页面)来解决这个问题。在扩展器的“write”方法中,在顶部添加如下代码:

              if (typeof newValue == "string") {
                  newValue = newValue.replace(",", ".");
              }
      

      需要 if 语句来防止模型初始化时出错。首次创建模型时,该值很可能设置为数字而不是字符串,因此我们无法在此对象上调用 .replace 方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-09-22
        • 1970-01-01
        • 2012-05-31
        • 1970-01-01
        • 2017-04-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多