HTML 文本输入未使用 Knockout 绑定更新
HTML text input not updating with Knockout Bindings
我正在尝试为 DOB 输入字段自动添加斜线,但 Knockout 绑定效果不佳。
<input
name=x
size=10
maxlength=10
class="span12"
placeholder="Date of birth (MM/DD/YYYY)"
onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'/').replace(/^(\d\d\/\d\d)(\d+)$/g,'/').replace(/[^\d\/]/g,'')"
data-bind="value:visitor().dateOfBirth, valueUpdate:'keyup'" />
现在的问题是 Knockout Js 绑定不允许自动更新斜线值。当我在文本框中输入日期时,没有出现斜杠。如何为 myViewModel 设置订阅者以在值更改时修改值?
你应该按照这些思路做一些事情 - 注意你应该从你的 input
标签中删除内联的 onkeyup
并让你的视图模型处理它:
var vm = function () {
var self = this;
self.dateOfBirth = ko.observable();
self.insertSlashes = function () {
var currentValue = self.dateOfBirth();
self.dateOfBirth(currentValue
.replace(/^(\d\d)(\d)$/g,'/')
.replace(/^(\d\d\/\d\d)(\d+)$/g,'/')
.replace(/[^\d\/]/g,'')
);
}
}
ko.applyBindings(new vm());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<input
placeholder="Date of birth (MM/DD/YYYY)"
data-bind="value: dateOfBirth, valueUpdate:'keyup', event: { keyup: insertSlashes } "
/>
我正在尝试为 DOB 输入字段自动添加斜线,但 Knockout 绑定效果不佳。
<input
name=x
size=10
maxlength=10
class="span12"
placeholder="Date of birth (MM/DD/YYYY)"
onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'/').replace(/^(\d\d\/\d\d)(\d+)$/g,'/').replace(/[^\d\/]/g,'')"
data-bind="value:visitor().dateOfBirth, valueUpdate:'keyup'" />
现在的问题是 Knockout Js 绑定不允许自动更新斜线值。当我在文本框中输入日期时,没有出现斜杠。如何为 myViewModel 设置订阅者以在值更改时修改值?
你应该按照这些思路做一些事情 - 注意你应该从你的 input
标签中删除内联的 onkeyup
并让你的视图模型处理它:
var vm = function () {
var self = this;
self.dateOfBirth = ko.observable();
self.insertSlashes = function () {
var currentValue = self.dateOfBirth();
self.dateOfBirth(currentValue
.replace(/^(\d\d)(\d)$/g,'/')
.replace(/^(\d\d\/\d\d)(\d+)$/g,'/')
.replace(/[^\d\/]/g,'')
);
}
}
ko.applyBindings(new vm());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<input
placeholder="Date of birth (MM/DD/YYYY)"
data-bind="value: dateOfBirth, valueUpdate:'keyup', event: { keyup: insertSlashes } "
/>