【原創】knockout--添加radio的checked綁定

直接上代碼:javascript

<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被選中。java

剛開始我覺得checked的有效值是true或false,後來才清楚原來有效值是radio的value屬性。spa

相關文章
相關標籤/搜索