Knockout.js 如何使用KnockoutJS使输入仅在下拉选择等于值时可见

Knockout.js 如何使用KnockoutJS使输入仅在下拉选择等于值时可见,knockout.js,Knockout.js,我是KnockoutJS新手,无法让文本和输入“Other Reason”仅在下拉菜单中选择“Other”时可见。请帮忙 <div id="reasonPopup" class="selectItems" style="display: none; position: absolute; width: 200px; height: 150px;"> Choose an Reason:<br /> <select data-bind="options: reasons

我是KnockoutJS新手,无法让文本和输入“Other Reason”仅在下拉菜单中选择“Other”时可见。请帮忙

<div id="reasonPopup" class="selectItems" style="display: none; position: absolute; width: 200px; height: 150px;">
Choose an Reason:<br />
<select data-bind="options: reasons,
optionsText: 'reasonText',
optionsValue: 'reasonValue',
value: chosenReason,
optionsCaption: 'Choose...'"></select>

<p data-bind="with: chosenReason">
    Other Reason: <input data-bind="value: $root.chosenReason, visible: chosenReason == 'Other'" />
    </p>

<p data-bind="with: chosenReason">
    You have chosen <b data-bind="text: $root.chosenReason"></b> 
</p>
<br />
<input type="button" data-bind="click: setReason('OK'), enable: chosenReason" value="OK" />
<input type="button" data-bind="click: setReason('Cancel'), disable: chosenReason" value="Cancel" />
<br />

选择原因:

其他原因:

你选择了




在绑定中使用
可见:chosenReason()。当您打算比较可观测值的当前值时,您当前正在将可观测值与“其他”进行比较

另一种方法是在视图模型中包含另一个可观察对象,然后绑定到该对象:

self.isOtherReason = ko.computed(function () {
    return self.chosenReason() === 'Other';
});

在包含
上执行
可见的
绑定也有意义,而不是直接在
上执行绑定

其他原因:

你选择了


基本上,您需要使用if绑定来根据条件比较要显示的内容。

看起来像是您应该在VM中执行的操作。但是,您可以使用。请向我们展示您的视图模型。Timothy,谢谢,但我已经找到了该示例,但它不适用于我的setup@user3431140定义“不起作用”。问题很明显,你没有包括括号。修复了。。。可见:chosenReason()。。。括号是我需要习惯的击倒JS的部分。。。对不起,我不能标记为答案。。。我没有足够的声望点数来这么做
<p data-bind="if: chosenReasonId() === 'Other'">
    Other Reason: <span data-bind="text: chosenReasonId"></span>
    </p>

<p data-bind="ifnot: chosenReasonId() === 'Other'">
    You have chosen <b data-bind="text: chosenReasonId"></b> 
</p>