Knockout js 条件选项绑定

Knockout js conditional options binding

本文关键字:绑定 选项 条件 js Knockout      更新时间:2023-09-26

在 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

查看此演示

你可以这样做:

 <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);
})​

试试这个演示

这是 2017 年的更新: 执行此操作的最佳方法(尤其是没有无容器条件绑定)来自后处理选项绑定的挖空文档,使用 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);
})​