【问题标题】:KnockoutJS Bind checkbox visibility to checkbox being checked OR having a certain valueKnockoutJS 将复选框可见性绑定到被选中的复选框或具有特定值
【发布时间】:2013-10-29 04:16:46
【问题描述】:

所以我有一个复选框,我正在尝试实现以下逻辑来设置可见性:

如果选中复选框或复选框的值低于指定数字,则设置可见 = true。

如果值超过测试值并且复选框没有被选中,隐藏它。

这是我目前所拥有的:

<input type="checkbox" data-bind="visible: $data.Cost <= $root.itemLevel() - $root.totalEnchantLevelsUsed() || checked" />

我尝试了几种“检查”的变体,包括将“检查”更改为 $root.isChecked:

this.isChecked = ko.computed ( function (item) { 
  console.log('item', item); // PURELY TO TEST THE VALUE
}

但这告诉我“项目”是未定义的。当我尝试显式传入 $data 时,我收到一条关于 ko.computed 并且必须设置“写入”访问权限的错误消息。

我只是忽略了一种相对简单的方法来做到这一点吗?诚然,我对淘汰赛不是很熟悉。

【问题讨论】:

    标签: javascript checkbox knockout.js


    【解决方案1】:

    这与您正在尝试做的事情类似:http://jsfiddle.net/2aXrJ

    HTML:

    <div data-bind="foreach:items">
        <label data-bind="visible: isAllowedInWorkflow">
            <input data-bind="value: val" type="checkbox" />
            This checkbox has value
            <span data-bind="text:val"></span>
        </label>
    </div>
    

    jS:

    ko.applyBindings({
        items: [createItem(10), createItem(20), createItem(30) ]
    })
    
    function createItem(val) {
        var  _item = {
             val: val
            ,isSelected: ko.observable(false)
        };
        _item.isAllowedInWorkflow = ko.computed(function() {
            //notice the order is importeant since you always want isSelected to be triggered for the 
            //computed to calculate its dependencies
            return !_item.isSelected() && val > 10; 
        });
        return _item;
    }
    

    【讨论】:

    • 我希望不必走这条路,因为这意味着必须重做一些我已经实现的代码,而这只是一个“很高兴拥有”的功能。但是,我想它就是这样。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2014-05-27
    • 2014-01-25
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    相关资源
    最近更新 更多