javascript 淘汰赛 js 复选框检查绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18062306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:37:27  来源:igfitidea点击:

Knockout js checkbox checked binding

javascriptknockout.js

提问by gth685f

In knockout js am trying to perform a foreach on an array of data to display check boxes. The issue I am having is that the checked databind does not appear to run until I interact with one of the boxes. For example, below I am generating 5 text boxes none of which are showing up as checked. However when I click "one", "two" and "four" also get checked as they should have been from the beginning.

在淘汰赛 js 中,我试图对数据数组执行 foreach 以显示复选框。我遇到的问题是,在我与其中一个框交互之前,所检查的数据绑定似乎不会运行。例如,下面我生成了 5 个文本框,其中没有一个显示为选中状态。但是,当我单击“一”时,“二”和“四”也会被检查,因为它们应该从一开始就被检查。

Javascript:

Javascript:

var viewModel = {};

viewModel.choices = ["one", "two", "three", "four", "five"];
viewModel.selectedChoices = ko.observableArray(["two", "four"]);

viewModel.selectedChoicesDelimited = ko.dependentObservable(function () {
        return viewModel.selectedChoices().join(",");
    });

ko.applyBindings(viewModel);

HTML:

HTML:

<ul class="options" data-bind="foreach: choices">
    <li><label><input type="checkbox" name="NotifyMembers" data-bind="checked: $parent.selectedChoices, attr: { value: $data }" /><span data-bind="text: $data"></span></label></li>
</ul>
<hr />
<div data-bind="text: selectedChoicesDelimited"></div>

Fiddle is at: http://jsfiddle.net/bvGG3/1/

小提琴位于:http: //jsfiddle.net/bvGG3/1/

Thanks for your help.

谢谢你的帮助。

回答by nemesv

In Knockout before version 3.0 the bindings fired in order, so your problem is that your checkedbinding fires before your attrbinding.

在 3.0 版之前的淘汰赛中,绑定按顺序触发,因此您的问题是checked绑定在attr绑定之前触发。

So you need to change the order of your bindings:

因此,您需要更改绑定的顺序:

<input type="checkbox" name="NotifyMembers" 
       data-bind="attr: { value: $data }, checked: $parent.selectedChoices" />

Demo JSFiddle.

演示JSFiddle

Or your original code will work when you update to 3.0 (demo JSFiddle).

或者当您更新到 3.0(演示JSFiddle)时,您的原始代码将起作用。