使用带有 knockoutjs 的单选按钮
using radio button with knockoutjs
通常我可以在 knockoutjs 中使用单选按钮,如下所示:
<input type="radio" value=1 data-bind="checked: groupvalue" /><span data-bind="text: 1"></span
但是如果我想从数组中动态获取值怎么办..
以下无效..
<tbody data-bind="foreach: colors">
<tr><td><input type="radio" data-bind="checkedValue:$data, checked: groupvalue" /><span data-bind="text: $data"></span></td></tr>
</tbody>
颜色是:
self.colors = ko.observableArray([
'Red',
'Green',
'Blue',
'Brown',
'Yellow',
'White',
'Black'
]);
我已经看到 this 但我希望得到一个简单的答案。
真诚感谢任何帮助。
谢谢
我认为你唯一的问题是 groupvalue
没有在正在迭代的模型中定义,所以如果你查看控制台,你会看到一个错误:
Unable to process binding "foreach: function (){return colors }"
Message: Unable to process binding "checked: function (){return groupvalue }"
Message: groupvalue is not defined
这会停止进一步 javascript 工作。将绑定更改为某些东西(大概像 $root.groupvalue
),它工作得很好
<tbody data-bind="foreach: colors">
<tr><td><input type="radio" data-bind="checkedValue:$data, checked: $root.groupvalue" />
<span data-bind="text: $data"></span></td></tr>
您需要使用 $parent
跳出 foreach
上下文才能到达 groupvalue
<tbody data-bind="foreach: colors">
<tr>
<td>
<input type="radio" data-bind="checkedValue:$data, checked: $parent.groupvalue" /><span data-bind="text: $data"></span>
</td>
</tr>
</tbody>
这是一个Plunkr
通常我可以在 knockoutjs 中使用单选按钮,如下所示:
<input type="radio" value=1 data-bind="checked: groupvalue" /><span data-bind="text: 1"></span
但是如果我想从数组中动态获取值怎么办..
以下无效..
<tbody data-bind="foreach: colors">
<tr><td><input type="radio" data-bind="checkedValue:$data, checked: groupvalue" /><span data-bind="text: $data"></span></td></tr>
</tbody>
颜色是:
self.colors = ko.observableArray([
'Red',
'Green',
'Blue',
'Brown',
'Yellow',
'White',
'Black'
]);
我已经看到 this 但我希望得到一个简单的答案。
真诚感谢任何帮助。
谢谢
我认为你唯一的问题是 groupvalue
没有在正在迭代的模型中定义,所以如果你查看控制台,你会看到一个错误:
Unable to process binding "foreach: function (){return colors }" Message: Unable to process binding "checked: function (){return groupvalue }" Message: groupvalue is not defined
这会停止进一步 javascript 工作。将绑定更改为某些东西(大概像 $root.groupvalue
),它工作得很好
<tbody data-bind="foreach: colors">
<tr><td><input type="radio" data-bind="checkedValue:$data, checked: $root.groupvalue" />
<span data-bind="text: $data"></span></td></tr>
您需要使用 $parent
跳出 foreach
上下文才能到达 groupvalue
<tbody data-bind="foreach: colors">
<tr>
<td>
<input type="radio" data-bind="checkedValue:$data, checked: $parent.groupvalue" /><span data-bind="text: $data"></span>
</td>
</tr>
</tbody>
这是一个Plunkr