取消选择单选按钮,同时保持视图模型同步
我有一个单选组,允许用户(使用 jQuery 事件)取消选择以前的选择。我正在尝试添加 KnockoutJS 来跟踪更改,但视图模式与 UI 不同步。谁能建议我如何让两者同步?
我的查看代码:
<div id='test'>
<input data-bind="checked: asd" name='asd' type='radio' value="a"/>
<input data-bind="checked: asd" name='asd' type='radio' value="b"/>
<input data-bind="checked: asd" name='asd' type='radio' value="c"/>
</div>
<div>
<p>Linked Value: <span data-bind="text: asd"></p>
</div>
对应的JS:
$('#test input[type="radio"]').click(function (event) {
var checked = $(this).hasClass('checked');
if (checked) {
$(this).removeAttr('checked');
$(this).removeClass('checked');
}
else {
$(this).addClass('checked');
}
});
var viewModel = {
asd: ko.observable("a")
};
ko.applyBindings(viewModel);
可以在this fiddle中在线查看示例。
I have a radio group that allows the user (using jQuery events) to deselect previous selections. I am trying to add KnockoutJS to track changes, but the viewmodal gets out of sync with the UI. Can anyone suggest how I might get the two to be in sync?
My view code:
<div id='test'>
<input data-bind="checked: asd" name='asd' type='radio' value="a"/>
<input data-bind="checked: asd" name='asd' type='radio' value="b"/>
<input data-bind="checked: asd" name='asd' type='radio' value="c"/>
</div>
<div>
<p>Linked Value: <span data-bind="text: asd"></p>
</div>
Corresponding JS:
$('#test input[type="radio"]').click(function (event) {
var checked = $(this).hasClass('checked');
if (checked) {
$(this).removeAttr('checked');
$(this).removeClass('checked');
}
else {
$(this).addClass('checked');
}
});
var viewModel = {
asd: ko.observable("a")
};
ko.applyBindings(viewModel);
An example can be viewed here online in this fiddle.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为一个简单的方法是:
Updated Fiddle
I think that a simple way would be to do:
Updated Fiddle
您无需担心已检查的属性,这已经为您完成了。将您的活动更改为:
此处是您的小提琴分支
You don't need to worry about the checked attribute, that's done for you. Change your event to this:
Fork of your fiddle here