敲除JS从中选择一个项目

KnockoutJS Select item from foreach

本文关键字:一个 项目 JS 选择 敲除      更新时间:2023-09-26

我有一个foreach绑定

<table id="Table_OperationsGroup">
    <tbody data-bind="foreach: groupOperationsGroup">
        <!-- ko if: $index() < $root.groupOperationsGroup().length - 1 -->
        <tr>
            <td>
                <select data-bind="changeGroup: groupOperations,options: operators, optionsText: 'Name', value: groupOperations" style="width: 105px;margin-top:5px !important;margin-bottom:5px !important;margin-left:0px !important;"></select>
            </td>
        </tr>
        <!-- /ko -->
    </tbody>
</table>

.JS

ko.bindingHandlers.changeGroup = {
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        //some code to work with the select
    }
};

var groupOperationsTemplate = function () {
    var self = this;
    self.groupOperations = ko.observable(operators);
    self.lines = ko.observableArray([{
        operations: ko.observable()
    }]);
    self.addLine = function (line) {
        line.lines.push({
            operations: ko.observable(operators)
        })
    };
    self.removeLine = function (line) {
        if (self.lines().length > 1) {
            self.lines.remove(line);
        }
    };
};
var Filter = function () {
    var self = this;
    //self.template = ko.observableArray();    
    self.groupOperationsGroup = ko.observableArray([new groupOperationsTemplate()]);
    self.addGroupOperator = function (data) {
        self.groupOperationsGroup.splice(self.groupOperationsGroup.indexOf(data) + 1, 0, new groupOperationsTemplate());
    };
};
var vm = new Filter();
ko.applyBindings(vm);

所以,我想要的是,如果有人更改了选择,我想准确地选择在绑定处理程序中更改的选择。问题是,每个选择都会调用绑定处理程序。它从 0 开始,然后是 1,2,3,依此类推。我希望你明白我的意思。

让我们在这里讨论。

运算符是一个数组,你用它来绑定选择

self.groupOperations = ko.observable(operator);

而不是

self.groupOperations = ko.observableArray([ { "Name": "Und", "Wert": 0 }, { "Name": "Und nicht", "Wert": 1 }, { "Name": "Oder", "Wert": 2 }, { "Name": "Oder nicht", "Wert": 3 } ]);
self.selectedValue = ko.observable();
self.selectedValue.subscribe(function( newValue) {
   //do whatever you want with new value
});

绑定到 select 时

 <!-- ko if: $index() < $root.groupOperationsGroup().length - 1 -->
        <tr>
            <td>
                <select data-bind="options: groupOperations, optionsText: 'Name', value: selectedValue" style="width: 105px;margin-top:5px !important;margin-bottom:5px !important;margin-left:0px !important;"></select>
            </td>
        </tr>
 <!-- /ko -->