0

我尝试简单地演示来自 knockout.js 教程的单选按钮绑定,但它不能按原样工作。例如,评论说应该检查 msg 值,但事实并非如此。

文档链接在这里http://knockoutjs.com/documentation/checked-binding.html

<p>Send me spam: <input type="checkbox" data-bind="checked: wantsSpam" /></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") // Initially selects only the Almond radio button
    };

    // ... then later ...
    viewModel.spamFlavor("msg"); // Now only Monosodium Glutamate is checked​

​</p>

这是链接http://jsfiddle.net/HhXGH/55/

4

1 回答 1

0

您在底部缺少这一行:

ko.applyBindings(viewModel);​</p>

仅供参考:如果您不知道 ko.applyBindings 是什么,以及它如何与 Knockout 绑定交互,请阅读此处的 Activating Knockout 部分:http: //knockoutjs.com/documentation/observables.html

编辑:更新的小提琴

http://jsfiddle.net/jearles/HhXGH/56/

于 2012-05-26T18:56:42.340 回答