问题
How can I achieve the following, when arrow keys are pressed it should go to the curresponding cell and enter the cell so the user can start typing right away without having to enter the cell first, and if the arrow keys are pressed in a numeric cell it should ignore the default behavior of adding or subtracting numbers and instead go to the upper or lower cell in the next row.
EDIT:
Here is the code I came up with but it only works sometimes and sometimes it will skip a cell or two, any advice?
$(document).ready(function () {
var grid = $("#grid").data("kendoGrid");
$(grid.tbody).on("keydown", "td",function (e) {
if (e.keyCode >= 37 && e.keyCode <= 40) {
var row = $(this).closest("tr");
var rowIndex = $("tr", grid.tbody).index(row);
var colIndex = $("td", row).index(this);
grid.closeCell();
if (e.keyCode == 37) {//left
colIndex--;
}
if (e.keyCode == 38) {//up
rowIndex--;
}
if (e.keyCode == 39) {//right
colIndex++
}
if (e.keyCode == 40) {//down
rowIndex++
}
grid.editCell($("#grid tr:eq(" + rowIndex + ") td:eq(" + colIndex + ")"));
}
});
});
回答1:
You have a silly mistake in your code which prevents it to work. You know, Kendo's grid actually works with two tables togheter, one for the header, other for the body. So if you specify in your selector the body's table tbody
element(the header table doesn't haves that element), it will work:
grid.editCell($("#grid tbody tr:eq(" + rowIndex + ") td:eq(" + colIndex + ")"));
^^^^^ // add here the 'tbody' element
Demo.
Also, I have added a little logic at the end to user be able to loop through rows and cell while navigating.
It is such a simple feature which should be native in the widget, IMHO.
来源:https://stackoverflow.com/questions/43241378/kendo-grid-navigate-and-enter-cells-with-arrow-keys