我有一个对象列表,我循环并为它们创建单选按钮,然后我想将选择的对象存储在 observable 中,但我不知道该怎么做。这个小提琴是我试图做的事情的例子:jsfiddle.net/whx96806/,但它不起作用。
<div data-bind="foreach: items">
<input type="radio" name="test" data-bind="checkedValue: $data, checked: $root.chosenItem" />
<span data-bind="text: itemName"></span>
</div>
<div><p>You have selected: <span data-bind="text:JSON.stringify(chosenItem())"></span></p></div>
<button data-bind="click:print">Print</button>
和js代码:
function ViewModel () {
items= ko.observableArray([
{ itemName: 'Choice 1' },
{ itemName: 'Choice 2' }
]);
chosenItem= ko.observable();
print = function () { alert(chosenItem()); };
};
var vm = new ViewModel();
ko.applyBindings(vm);