我有一个复选框和一个文本框。只要未选中复选框,我希望文本框为空且不可编辑。
在未选中文本框时我必须禁用文本框的部分工作正常但清空部分工作不正常,因为我必须为其使用复选框的单击绑定(bind),并且一旦我使用单击绑定(bind),它就会破坏复选框行为它变得无法点击。我有一个 jsFiddle:http://jsfiddle.net/qK5Y3/16/
和下面的代码示例:
<input type="checkbox" id="emailTemplateSendAtTime" name="emailTemplateSendAtTime" data-bind="checked:SendAtTime, click:ClickSendAtTime"/>
<input type="text" style="width: 250px" id="emailTemplateSendAtTimeProperty" data-bind="value: SendAtTimeProperty, enable:SendAtTime"/>
这是我的js:
var ViewModel = function () {
this.SendAtTimeProperty = ko.observable("Something");
this.SendAtTime = ko.observable();
this.ClickSendAtTime = function () {
if (model.SendAtTime() == false) {
model.SendAtTimeProperty("");
}
};
};
ko.applyBindings(new ViewModel());
有什么建议吗?
最佳答案
两件事:
- 添加
模型
作为ClickSendAtTime
的参数> 在
ClickSendAtTime
上返回 true 以避免取消事件var ViewModel = function () { this.SendAtTimeProperty = ko.observable("Something"); this.SendAtTime = ko.observable(); this.ClickSendAtTime = function (model) { if (model.SendAtTime() == false) { model.SendAtTimeProperty(""); } return true; }; }; ko.applyBindings(new ViewModel());
定义ClickSendAtTime
的另一种方式
this.ClickSendAtTime = function () {
if (this.SendAtTime() == false) {
this.SendAtTimeProperty("");
}
return true;
};
关于为什么需要返回 true 的一些信息
Allowing the default action
By default, Knockout will prevent the event from taking any default action. For example if you use the event binding to capture the keypress event of an input tag, the browser will only call your handler function and will not add the value of the key to the input element’s value. A more common example is using the click binding, which internally uses this binding, where your handler function will be called, but the browser will not navigate to the link’s href. This is a useful default because when you use the click binding, it’s normally because you’re using the link as part of a UI that manipulates your view model, not as a regular hyperlink to another web page.
However, if you do want to let the default action proceed, just return true from your event handler function.
关于javascript - 单击复选框的绑定(bind)在 Knockout 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16862524/