更新计算后如何设置输入焦点

How to set focus of input after computed has been updated

我有 table/grid 根据类型显示设备。每当下拉列表发生变化时,table 应该更新以显示正确的设备。为此,我有一个计算器可以按类型过滤设备并向 table/grid.

添加一个新的空白行

这是 html:

<table>
    <thead>
        <tr>
            <th><!--Row Number--></th>
            <th>Serial No.</th>
            <th>Name</th>
            <th><!--Delete Button--></th>
        </tr>
    </thead>
    <tbody data-bind="foreach: filteredDevices">
        <tr>
            <td data-bind="text: $index() + 1"></td>
            <td><input data-bind="value: serial, event: { change: ($parent.filteredDevices().length == $index() + 1) ? $parent.addDevice : '' }" /></td>
            <td><input data-bind="value: name, event: { change: ($parent.filteredDevices().length == $index() + 1) ? $parent.addDevice : '' }" /></td>
            <td><button type="button" data-bind="visible: $parent.filteredDevices().length != $index() + 1, click: $parent.deleteDevice">Delete</button></td>
        </tr>
    </tbody>
</table>

淘汰代码:

var DevicesViewModel = function () {
    var self = this;

    self.devices = ko.observableArray([{ name: 'test1', serial: 'test1', type: 'type1' },{ name: 'test2', serial: 'test2', type: 'type2' }]);
    self.selectedDeviceType = ko.observable("type1");

    self.deviceTypes = ko.observableArray([
        { value: 'type1', name: 'Type 1' },
        { value: 'type2', name: 'Type 2' }
    ]);

    self.addDevice = function (data) {
        self.devices.push({ name: data.name, serial: data.serial, type: data.type });
    };

    self.deleteDevice = function (device) {
        self.devices.remove(device);
    };

    self.filteredDevices = ko.computed(function () {
        var arr = ko.utils.arrayFilter(self.devices(), function (device) {
            return device.type == self.selectedDeviceType();
        });

        arr.push({ name: null, serial: null, type: self.selectedDeviceType() });

        return arr;
    });
};

ko.applyBindings(new DevicesViewModel());

这是它的 fiddle:https://jsfiddle.net/wa9108bf/

如果您最初通过 tab 键浏览网格,一切正常。但是,如果您在最后一行的第一个输入中键入内容并按 Tab 键结束,焦点就会丢失。我猜发生这种情况是因为计算已更新并且 table 再次使用对焦点一无所知的新计算数组进行渲染。有没有办法获得我想要的功能?

输入将失去焦点,因为您要删除当前项目并添加副本。如果您改为维护数组中的当前项,焦点将保持不变。

改变

self.addDevice = function (data) {
    self.devices.push({ name: data.name, serial: data.serial });
};

self.addDevice = function (data) {
    self.devices.push(data);
};