Javascript 如何在Knockout.js中正确清除复选框单击上的另一个字段?

Javascript 如何在Knockout.js中正确清除复选框单击上的另一个字段?,javascript,html,knockout.js,Javascript,Html,Knockout.js,我有一个复选框列表,其中一个是“其他”,我想要的是,如果选择了“其他”,则会启用一个文本框。如果未选中“其他”,则必须禁用文本框并清除其内容 现在的问题是,当我点击“其他”复选框时,复选标记不会显示或消失,直到我触发另一个绑定事件。我必须通过将click事件处理程序添加到“Other”复选框中来进行淘汰 HTML 苹果公司 香蕉 其他 JS $(文档).ready(函数(){ var BaseVM=函数(){ var,它={}; 归还; }; var TestVM=函数(){ var=B

我有一个复选框列表,其中一个是“其他”,我想要的是,如果选择了“其他”,则会启用一个文本框。如果未选中“其他”,则必须禁用文本框并清除其内容

现在的问题是,当我点击“其他”复选框时,复选标记不会显示或消失,直到我触发另一个绑定事件。我必须通过将click事件处理程序添加到“Other”复选框中来进行淘汰

HTML

苹果公司
香蕉
其他 JS

$(文档).ready(函数(){
var BaseVM=函数(){
var,它={};
归还;
};
var TestVM=函数(){
var=BaseVM();
that.selectedFoods=ko.observearray(['apple','banana']);
that.otherFoods=ko.可观察(空);
that.otherClicked=函数(){
如果(that.selectedFoods.indexOf('other')<0){
其他食物='';
}
};
归还;
};
var vm=TestVM();
ko.应用绑定(vm);
});
这一行

that.otherFoods = '';
这是错误的。您需要将该值指定为可观察值,因为它是:

that.otherFoods('');
此外,在检查值时,还需要评估数组:

that.selectedFoods.indexOf('other') < 0
that.selectedFoods.indexOf('other')<0
应该是

that.selectedFoods().indexOf('other') < 0
that.selectedFoods().indexOf('other')<0
编辑:如果您的单击处理程序设置错误,请参阅此更新的小提琴:


您需要在单击处理程序中返回true,以使复选框仍像复选框一样工作。此外,您正在使用文本绑定而不是文本框上的值绑定。

首先,您需要从
单击处理程序
返回true
,否则本机事件将不会传播,复选框状态也不会更改

此外,当重置可观察的
otherFoods
时,您需要调用可观察的,而不是覆盖它:

that.otherClicked = function () {
    if (that.selectedFoods.indexOf('other') < 0)
        that.otherFoods('');

    return true;
};

请看

好球!另外,我需要将文本框的绑定从
text
更改为
value
that.selectedFoods().indexOf('other') < 0
that.otherClicked = function () {
    if (that.selectedFoods.indexOf('other') < 0)
        that.otherFoods('');

    return true;
};
<input type='text' data-bind="value: otherFoods, attr:{disabled: selectedFoods.indexOf('other') < 0}" />