在淘汰赛中制作仅输入数字类型

IT技术 javascript knockout.js knockout-2.0
2021-03-12 02:07:25

我阅读了很多教程,但我不知道该怎么做,这是输入

input(type="text",name="price",id="price"data-bind="text: price,valueUpdate:['afterkeydown','propertychange','input']")

这是我的 viewModel

price: ko.computed(function()
{
    return parseFloat(this.replace(' ','').replace(/[^0-9\.]+/g,"")) || '';
},this)

但这会导致错误:这没有方法替换???如何将价格值传递给计算函数?

6个回答

最好创建自定义绑定http://knockoutjs.com/documentation/custom-bindings.html只接受允许的字符 [0-9,.] 作为数字表示。

将此行放入您的视图中

<input id="text" type="text" data-bind="numeric, value: number">

将此行放入您的模型中(记住将数字绑定为可观察属性)

ko.bindingHandlers.numeric = {
    init: function (element, valueAccessor) {
        $(element).on("keydown", function (event) {
            // Allow: backspace, delete, tab, escape, and enter
            if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
                // Allow: Ctrl+A
                (event.keyCode == 65 && event.ctrlKey === true) ||
                // Allow: . ,
                (event.keyCode == 188 || event.keyCode == 190 || event.keyCode == 110) ||
                // Allow: home, end, left, right
                (event.keyCode >= 35 && event.keyCode <= 39)) {
                // let it happen, don't do anything
                return;
            }
            else {
                // Ensure that it is a number and stop the keypress
                if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                    event.preventDefault();
                }
            }
        });
    }
};
从输入字段更改焦点后,将应用更改。这是带有实时编辑的简单示例(无焦点更改)。 jsfiddle.net/jakethashi/L7UEm
2021-04-25 02:07:25
@renathy 我离开了 textInput 绑定,并添加了数字作为第二个绑定,效果很好
2021-04-27 02:07:25
这真的有效吗?对我来说,如果它在 UI 上的某个地方,它不会更新 Observable 吗?例如,您有上面的 <input ...> 和一些 <span data-bind="text: number"></span>。在这种情况下,如果用户在输入中编辑数字,则编辑完成后不会更新 UI。
2021-05-05 02:07:25
捷克语键盘也不起作用,这也需要 Shift+number 才能工作。
2021-05-09 02:07:25
你如何处理荷兰语键盘?数字在哪里 Shift + Key ?
2021-05-14 02:07:25

淘汰赛为此提供了扩展程序。从knockoutjs.com检查这个解释如何使用可观察扩展器强制输入为数字。我将文档中的代码粘贴到此处:

源代码:查看

<p><input data-bind="value: myNumberOne" /> (round to whole number)</p>
<p><input data-bind="value: myNumberTwo" /> (round to two decimals)</p>

源代码:查看模型

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;
};

function AppViewModel(one, two) {
    this.myNumberOne = ko.observable(one).extend({ numeric: 0 });
    this.myNumberTwo = ko.observable(two).extend({ numeric: 2 });
}

ko.applyBindings(new AppViewModel(221.2234, 123.4525));

我有一个类似的问题。

我还需要仅确保内部值,对于 IE9 及更高版本(因此 type=numberical 还不够),而且由于我们有很多国际客户,我也不能依赖键码,所以以下是我最终的结果和:

//In my js class method (self is this as usual)
self.ensureNumberical = function (data, e) {
    var keyValue = e.key;
    if (keyValue.match(/[0-9]/g)) {
        return true;
    }
    return false;
}

//In my MVC View
data-bind="event: { keypress: ensureNumberical }"

另一种方法:我发现 Knockout 与jQuery-validate结合使用效果很好您只需要确保在尝试使用数值之前验证表单。

假设你有一个表单 DOM 元素,你可以通过设置验证规则

$(".yourform").validate({
    rules: {
        year: {
            digits: true,
            minlength: 4,
            maxlength: 4
        }
    },
    messages: {
        year: "Please enter four digits (e.g. 2009).",
    }
});

在您的视图模型中,您像往常一样设置双向绑定,例如 via self.year = ko.observable("")现在确保$(".yourform").valid()在进一步处理之前调用self.year()就我而言,我正在做var year = parseInt(self.year(), 10). 在表单验证之后,这预计总是会产生有意义的结果。

最适合今天的场景 https://github.com/Knockout-Contrib/Knockout-Validation

运行下面的代码片段。输入非数字或大于 255 的内容将导致显示消息。

function model() {
  var self = this;
  this.myObj = ko.observable().extend({ digit: true }).extend({ max: 255});
  }
  
  var mymodel = new model();

$(document).ready(function() {
  ko.validation.init();
  ko.applyBindings(mymodel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script>

enter a digit less than or equal to  255 <input type="text" data-bind="textInput: myObj">

<p>
  Enter something other than a digit or over 255 will cause an error.
</p>

礼貌:布莱恩德林格:https ://stackoverflow.com/a/42940109/3868653