根据单选按钮值设置HTML代码段的可见性

时间:2013-08-12 17:27:50

标签: knockout.js

我想制作一些HTML,例如<p>Only visible if almond checked</p>,仅在选中value="almond"的单选按钮时可见。

这是我尝试过的。观点:

<p>Send me spam: <input type="checkbox" data-bind="checked: wantsSpam" /></p>
<p>Only visible if almond checked</p>
<div data-bind="visible: wantsSpam">
    Preferred flavor of spam:
    <div><input type="radio" name="flavorGroup" value="cherry" data-bind="checked: spamFlavor" /> Cherry</div>
    <div><input type="radio" name="flavorGroup" value="almond" data-bind="checked: spamFlavor" /> Almond</div>
    <div><input type="radio" name="flavorGroup" value="msg" data-bind="checked: spamFlavor" /> Monosodium Glutamate</div>
</div>

这个视图模型:

 var viewModel = {
        wantsSpam: ko.observable(true),
        spamFlavor: ko.observable("almond")
    };

ko.applyBindings(viewModel);

另见this jsfiddle

1 个答案:

答案 0 :(得分:3)

最直接的方式是:

<p data-bind="visible: spamFlavor() === 'almond'">Only visible if almond checked</p>

请参阅this fiddle

通常,您希望将spamFlavor() == 'almond'位移动到具有某些含义的单独视图模型属性。也许是这样的:

<p data-bind="visible: almondSpecialVisible">Only visible if almond checked</p>

使用视图模型:

viewModel.almondSpecialVisible = ko.computed(function() { 
    return viewModel.spamFlavor() == 'almond'; 
});

请参阅this fiddle