【原创】knockout--添加radio的checked绑定
直接上代码:
<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> <script type="text/javascript"> 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 </script>
这是官网上的一段代码,可以看出有三个radio,他们的checked属性都绑定在spamFlavor上,初值是“almond”,这样默认的value是“almond”的radio被选中。
刚开始我以为checked的有效值是true或false,后来才清楚原来有效值是radio的value属性。