我正在创建一个动态过滤器列表,该列表允许用户添加多个条件。该列表由一个选择元素和两个输入字段组成。最初只应显示一个字段。仅当选择值BETWEEN时,才显示第二个字段。我看到了使用on select元素设置元素可见性的示例。
这是我到目前为止的内容:

js

function FilterList(Operator, FilterCriteria, FilterCriteriaRange) {
    var self = this;
    self.operator = ko.observable(Operator);
    self.criteria1 = ko.observable(FilterCriteria);
    self.criteria2 = ko.observable(FilterCriteriaRange);
}

function AppViewModel() {
    var self = this;

    self.filterOperators = ko.observableArray([{
        operatorName: "EQUALS",  operatorValue: "=" }, {
        operatorName: "GREATER THAN", operatorValue: ">"}, {
        operatorName: "GREATER THAN OR EQUAL TO", operatorValue: ">="}, {
        operatorName: "LESS THAN", operatorValue: "<" }, {
        operatorName: "LESS THAN OR EQUAL TO", operatorValue: "<=" }, {
        operatorName: "NOT EQUAL TO", operatorValue: "<>" }, {
        operatorName: "NOT LESS THAN", operatorValue: "!>" }, {
        operatorName: "NOT GREATER THAN", operatorValue: "!<" }, {
        operatorName: "BETWEEN", operatorValue: "BETWEEN" }, {
        operatorName: "LIKE",  operatorValue: "LIKE"
    }]);
    //define filter collection
    self.myfilters = ko.observableArray([]);
    self.addFilter = function () {
        self.myfilters.push(new FilterList(self.filterOperators[0]));
    };

    self.inputVisible = ko.computed(function(){
        //retrieve the selected value of the current row and display the second criteria field if the selected value is BETWEEN
        //return self.operator();
    });
}
ko.applyBindings(new AppViewModel());


html

<input type="button" value="Add Filter" title="Add Group" data-bind="click: $root.addFilter" />
<table>
   <tbody data-bind="foreach: myfilters">
     <tr>
     <td>
       <select data-bind="options: $root.filterOperators, value:operator, optionsText:'operatorName'"></select>
     </td>
     <td>
       <input data-bind="value: criteria1" />
      </td>
     <td>
      <input data-bind="value: criteria2, visible: inputVisible() === 'BETWEEN'" />
     </td>
    </tr>
    </tbody>
</table>


卡住的地方是获取要与之交互的当前行的正确值。该链接http://jsfiddle.net/rlcrews/R6Kcu/提供了一个工作提琴,显示了正在生成的行,我只是停留在如何从选择行中导出选择的值上。

最佳答案

这是您要找的东西吗? http://jsfiddle.net/pyvJW/1/

由于要遍历myfilters,因此可以访问operator字段。由于运算符是可观察的,因此只需要括号即可访问operatorName。

<input data-bind="value: criteria2, visible: operator().operatorName === 'BETWEEN'" />

关于javascript - 如何使用knockout.js根据现有数组中选择元素的选择值设置输入字段的可见性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16865057/

10-12 00:20
查看更多