我觉得真的很蠢,但不能让它工作:)
我做了这个简单的小提琴只是为了证明我在大项目中没有遗漏任何东西.
HTML:
<div> Preferred flavor <div><input type="radio" name="flavorGroup" data-bind="checked: cherryOn" /> Cherry</div> <div><input type="radio" name="flavorGroup" data-bind="checked: almondOn" /> Almond</div> <div><input type="radio" name="flavorGroup" data-bind="checked: mgOn" /> Monosodium Glutamate</div> </div>
JS:
var viewmodel = { cherryOn: ko.observable(true); almondOn: ko.observable(false); mgOn: ko.observable(false); }; ko.applyBindings(viewmodel);
我希望在开始时选择Cherry.
解决方法
来自Knockout的文档(
http://knockoutjs.com/documentation/checked-binding.html):
For radio buttons,KO will set the element to be checked if and only
if the parameter value equals the radio button node’s value attribute.
示例:http://jsfiddle.net/btkmR/2/
<div> Preferred flavor <div><input type="radio" name="flavorGroup" value="cherry" data-bind="checked: flavor" /> Cherry</div> <div><input type="radio" name="flavorGroup" value="almond" data-bind="checked: flavor" /> Almond</div> <div><input type="radio" name="flavorGroup" value="Monosodium" data-bind="checked: flavor" /> Monosodium Glutamate</div> </div> var viewmodel = { flavor: ko.observable("cherry") }; ko.applyBindings(viewmodel);