[英]KnockoutJS checked binding with radio button
我有一個要遍歷的對象列表,並為其創建單選按鈕,然后我想將所選對象存儲在可觀察對象中,但是我不知道該怎么做。 這個小提琴是我正在嘗試做的事的示例: 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);
這是小提琴: http : //jsfiddle.net/whx96806/1/
請嘗試此代碼段,看看是否有幫助:
var ViewModel = {
items : ko.observableArray([
{ itemName: 'Choice 1' },
{ itemName: 'Choice 2' }
]),
chosenItem : ko.observable(),
};
ko.applyBindings(ViewModel);
問題是我忘了在視圖模型中使用“ this”,這應該可以工作:
function ViewModel () {
this.items= ko.observableArray([
{ itemName: 'Choice 1' },
{ itemName: 'Choice 2' }
]);
this.chosenItem= ko.observable();
print = function () { alert(chosenItem()); };
};
var vm = new ViewModel();
ko.applyBindings(vm);
這是小提琴: http : //jsfiddle.net/whx96806/2/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.