【问题标题】:Preventing all checkboxes from being set to true/false when one is clicked防止单击一个复选框时将所有复选框设置为真/假
【发布时间】:2018-01-22 18:51:09
【问题描述】:

我在 Knockout 中工作,我正在尝试在选中特定复选框时获取特定信息。但是,当我单击一个复选框时,正在发生的情况是每个复选框都被选中/取消选中。我的问题是,如何防止这种情况发生并使其仅选中/取消选中我选择/取消选中的复选框?

JS 我已经对此进行了简化,只显示我正在使用的代码。

export class Model{
    isSelected: KnockoutObservable<boolean>;
    constructor(){
        this.isSelected = ko.observable(false);
    }
    selectStuff = () => {
        return true;
    }
}

HTML

<div data-bind="foreach: stuffToLoopThrough">
    <input type="checkbox" class="checkbox" name="checkBox" data-bind="checked: $root.isSelected, click: $root.selectStuff" />Send Stuff

    <input type="checkbox" class="checkbox" name="checkBox" data-bind="checked: $root.isSelected, click: $root.selectStuff" />Send Stuff

    <input type="checkbox" class="checkbox" name="checkBox" data-bind="checked: $root.isSelected, click: $root.selectStuff" />Send Stuff
</div>

所以这里发生的情况是,如果我要单击三个复选框之一,每个复选框都会被选中,我只想选中我选择的复选框。我该如何做到这一点?我哪里错了?

【问题讨论】:

  • 它们都绑定到同一个变量。您需要在 stuffToLoopThrough 的每个项目中绑定一个 observable。

标签: javascript checkbox knockout.js


【解决方案1】:

您想要选择多个值还是只选择一个?如果您只想 1 使用收音机而不是复选框。

无论哪种方式,请查看checkedValue 绑定,它允许您将结果存储在变量中:

http://knockoutjs.com/documentation/checked-binding.html

var stuffToLoopThrough = Model[];
var selectedValue = ko.observable();

    export class Model{
    isSelected: KnockoutObservable<boolean>;
    constructor(){
        this.uniqueValueOrId= ko.observable();
        this.isSelected = ko.observable(false);
    }
    selectStuff = () => {
        return true;
    }
}

然后是html

<div data-bind="foreach: stuffToLoopThrough">
    <input type="radio"
           class="radio" 
           name="checkBox" 
           data-bind="checked:  isSelected, 
           checkedValue: $root.uniqueValueOrId, 
           click: $root.selectStuff"> Send Stuff
</div>

请注意,我没有使用 $root 进行检查...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多