使用Jquery更改值时KnockoutJS属性不会更新

编程入门 行业动态 更新时间:2024-10-21 12:01:31
本文介绍了使用Jquery更改值时KnockoutJS属性不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一系列的复选框,我想收集所选的复选框.复选框位于div中,单击div时也应选中该复选框:

I have a serie of checkboxes and I want to gather the selected one. The checkboxes are in div's and when the div is clicked the checkbox should get checked as well:

var oCheckBox = $($(this).find('.chkSocialMediaItem').get(0)); oCheckBox.attr('checked', !$(oCheckBox).attr('checked'));

这很好用,但KnockoutJS不会接受更改,因此不会更新所选项目的计数器.

This works just fine but KnockoutJS doesn't pick up the change and so doesn't update my counter on the selected items.

我在某个地方读到需要触发变更事件的地方.但是,当我在复选框上监听更改事件时,它实际上确实会被触发.

I read somewhere you need to trigger the change event. But when I listen to the change event on the checkbox it does actually get triggered.

任何帮助,我们将不胜感激, 谢谢!

Any help would be appreciated, Thanks !

更新:

我找到了一种淘汰赛"解决方案. 在我的div中,我对"click"进行了数据绑定,并更改了该函数中的检查值:

I have found a 'knockout' solution. In my div I did a data-bind off the 'click' and changed the checked value in that function:

<script type="text/html" id="Template"> <div class="item" data-bind="click: DivClicked"> <input type="checkbox" data-bind="checked: IsASelectedItem" class="chkSocialMediaItem"/> </div> </script> function SocialMediaSearchItem() { this.IsASelectedItem = ko.observable(); this.DivClicked = function () { this.IsASelectedItem(!this.IsASelectedItem()); }; }

这是唯一的解决方案吗?我真的很想2也看到一个Jquery解决方案.

Is this the only solution? I would really like 2 see a Jquery solution as well.

推荐答案

checked绑定仅侦听click事件.手动触发click事件最终会导致框基于设置实际检查值的时间不同步.

The checked binding only listens to the click event. Manually triggering the click event ends up getting the box out-of-sync based on when the actual checked value is set.

设置值的首选方法是更新视图模型值,就像在上面的第二个示例中所做的那样.

The preferred way to set the value is to update your view model value, as you have done in your second example above.

但是,如果您使用的是 1.3beta ,那么就有一种简单的方法可以使用ko.dataFor API将元素与其相应的数据连接起来.看起来像这样:

However, if you are using 1.3beta, then there is an easy way to connect an element with its corresponding data using the ko.dataFor API. It would look something like:

var oCheckBox = $('.chkSocialMediaItem'), data = ko.dataFor(oCheckBox[0]); data.selectedItem(!data.selectedItem());

更多推荐

使用Jquery更改值时KnockoutJS属性不会更新

本文发布于:2023-11-11 23:27:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579832.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   Jquery   KnockoutJS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!