我正在用表格显示搜索结果。每个结果都有一个按钮供用户单击以显示其详细信息。很好

我还想要通过使用键盘的向上和向下箭头来导航搜索结果。

现在,用户必须单击Select按钮或该按钮的选项卡,然后按space bar

我想我可以捕获keyup和down事件,然后找到需要选择的上一个或下一个,然后进行设置,但这听起来很繁琐。我想知道是否有更好的方法?

javascript

var myModel = new function() {
    var self = this;

    self.selectedResult = ko.observable(new MyObj());
    self.searchResults = ko.observableArray();
    self.navUpDown = function (item, evt) {
        if (evt.keyCode == 38) { // up
            var id = item.ID();
            // find previous one and set selectedResult
        }

        if (evt.keyCode == 40) { // down
            var id = item.ID();
            // find next one and set selectedResult
        }
    };
};

html
<table class="table">
    <thead>
        <tr>
            <th>&nbsp;</th>
            <th>table header 1</th>
            <th>table header 2</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: searchResults">
        <tr data-bind="css: { 'btn-info': $parent.selectedResult() == $data }, event: { keyup: $parent.navUpDown } ">
            <td>
                <button class="btn btn-small" data-bind="click: $parent.selectResult">Select</button>
            </td>
            <td data-bind="text: data1"></td>
            <td data-bind="text: data2"></td>
        </tr>
    </tbody>
</table>

最佳答案

我认为这就是您想要的。

var myModel = new function () {
        var self = this;
        self.selectResult = function (item) {
            self.selectedResult(item);
        };
        self.selectedResult = ko.observable();
        self.searchResults = ko.observableArray([{
            data1: "1",
            data2: "2"
        }, {
            data1: "2",
            data2: "2"
        }, {
            data1: "3",
            data2: "2"
        }]);


        self.selectPrevious = function () {
            var index = self.searchResults().indexOf(self.selectedResult()) - 1;
            if (index < 0) index = 0;
            self.selectedResult(self.searchResults()[index]);
        };

        self.selectNext = function () {
            var index = self.searchResults().indexOf(self.selectedResult()) + 1;
            if (index >= self.searchResults().length) index = self.searchResults().length - 1;
            self.selectedResult(self.searchResults()[index]);
        };


    };
ko.applyBindings(myModel);

$(window).keyup(function (evt) {
    if (evt.keyCode == 38) {
        myModel.selectPrevious();
    } else if (evt.keyCode == 40) {
        myModel.selectNext();
    }
});

See Fiddle

希望对您有所帮助。

07-24 16:25