Boo*_*one 2 jquery knockout.js
我有一份人员名单.对于每个人,我都有真假.我希望这个每个人都有约束力.如果您检查下面的小提琴,它正确绑定但我的单选按钮不能正常工作.我希望每一行都有自己的单选按钮(每行不同的名称).
例如.第1行单击为true,第2行单击为false.这应该是允许的,但名称与删除第一行的选择相矛盾.谢谢
<table width="300px;">
<thead>
<tr>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody data-bind="foreach: people">
<tr>
<td>
<span data-bind="text: Name"></span>
</td>
<td>
<input type="radio" name="Status" value="true" data-bind="checked: Status" />
<input type="radio" name="Status" value="false" data-bind="checked: Status" />
</td>
<td><button data-bind="click: $root.changeStatus">Change Status</button></td>
</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
function People(data) {
var self = this;
self.Name= data.Name;
self.Status = ko.observable(data.Status);
}
function PeopleViewModel(userId) {
var self = this;
self.people = ko.observable([
{ Name: 'Bert', Status: true },
{ Name: 'Charles', Status: true },
{ Name: 'Denise', Status: false }
]);
self.changeStatus = function()
{
alert("Change " + this.Name + " to " + this.Status);
};
}
ko.applyBindings(new PeopleViewModel());
Run Code Online (Sandbox Code Playgroud)
一些东西:
name所有人的属性都是一样的.您可以使用attr绑定并使用人员姓名为每个单选按钮组添加前缀来更改此设置.people一个observableArray而不仅仅是一个observable.Status如果您希望更新基础数据模型,则每个人的属性也应该是可观察的.value您分配Status到应该是一个字符串.这是修改后的代码及更新:
HTML:
<table width="300px;">
<thead>
<tr>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody data-bind="foreach: people">
<tr>
<td>
<span data-bind="text: Name"></span>
</td>
<td>
<input type="radio" value="true" data-bind="attr: { name: Name + '-status' }, checked: Status" />
<input type="radio" value="false" data-bind="attr: { name: Name + '-status' }, checked: Status" />
</td>
<td><button data-bind="click: $root.changeStatus">Change Status</button></td>
</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
JavaScript的:
function People(data) {
var self = this;
self.Name = data.Name;
self.Status = ko.observable(data.Status);
}
function PeopleViewModel(userId) {
var self = this;
self.people = ko.observableArray([
{
Name: 'Bert',
Status: ko.observable('true')
},
{
Name: 'Charles',
Status: ko.observable('true')
},
{
Name: 'Denise',
Status: ko.observable('false')
}]);
self.changeStatus = function() {
alert("Change " + this.Name + " to " + this.Status());
if (this.Status() === "true") {
this.Status('false');
} else {
this.Status('true');
}
};
}
ko.applyBindings(new PeopleViewModel());?
Run Code Online (Sandbox Code Playgroud)
示例: http ://jsfiddle.net/AKKvz/