【问题标题】:Knockout js conditional options bindingKnockout js条件选项绑定
【发布时间】:2012-08-17 07:21:48
【问题描述】:

在 Knockoutjs 中是否可以为选项绑定的子元素设置条件

例如:

viewModel.array([{name: 1, show: true}, {name: 2, show: false}, {name: 3, show: true}]);

<select data-bind="options: array, optionsText: name, if: show"></select>

将显示在选择框中:

1
3

【问题讨论】:

    标签: javascript html knockout.js


    【解决方案1】:

    查看此demo

    你可以这样做:

     <select  data-bind="value: selectedCountry , foreach : countryArray" >
           <!-- ko if: show -->        
                <option data-bind="value : name, text : name "></option>
           <!-- /ko -->
     </select> ​
    
    function viewModel() {
    
        var self = this;
        this.countryArray = ko.observableArray([{"name" : "France" ,"show" : true},
                                                {"name" : "Italy" , "show" : true},
                                                {"name":"Germany" , "show" : false}]);
    
        this.selectedCountry = ko.observable("");
    
    }
    
    $(document).ready(function() {
    
        var vm = new viewModel();
        ko.applyBindings(vm);
    
    })​
    

    【讨论】:

    • 对不起,我正在使用 linux 无法通过 IE 进行测试。你有什么错误吗?
    • 无容器条件绑定被忽略...似乎其他人也有这个问题:stackoverflow.com/questions/11723451/…
    【解决方案2】:

    试试这个demo

    这是 2017 年的更新:执行此操作的最佳方法(尤其是没有无容器条件绑定)来自 post-processing 选项绑定的淘汰文档,使用 optionsAfterRender 绑定。 optionsAfterRender 是在 2.3 版本中添加的

    您的代码将如下所示:

     <select  data-bind="value: selectedCountry , options : countryArray, optionsText: 'name', optionsAfterRender: setOptionsShow" ></select>  ​
    
    function viewModel() {
    
        var self = this;
        this.countryArray = ko.observableArray([{"name" : "France" ,"show" : true},
                                                {"name" : "Italy" , "show" : true},
                                                {"name":"Germany" , "show" : false}]);
    
        this.selectedCountry = ko.observable("");
        this.setOptionsShow = function(option, item) {
                ko.applyBindingsToNode(option, {visible: item.show}, item);
            }
    
    }
    
    $(document).ready(function() {
    
        var vm = new viewModel();
        ko.applyBindings(vm);
    
    })​
    

    【讨论】:

      猜你喜欢
      • 2015-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      • 2014-02-21
      • 1970-01-01
      相关资源
      最近更新 更多