layui 框架 table插件 实现键盘快捷键 切换单元格编辑

// 使用方法:
//1.在需要启用此功能的页面中table done回调函数中插入。
//2.修改源代码,在源代码中直接插入,此方法就不需要在每一个页面的table done回调函数中 插入。
//注:单元格必须开启了 edit:text 模式,才支持键盘切换。
$(document).on(keydown, .layui-table-edit, function(e) {
          
   
    var td = $(this).parent(td),
    tr = td.parent(tr),
    trs = tr.parent().parent().find("tr"),
    tr_index = tr.index(),
    td_index = td.index(),
    td_last_index = tr.find([data-edit="text"]:last).index(),
    td_first_index = tr.find([data-edit="text"]:first).index();
    switch (e.keyCode) {
          
   
         case 13: //enter
         case 39: //右
             td.nextAll([data-edit="text"]:first).click();
             if (td_index == td_last_index) {
          
   
                  tr.next().find(td).eq(td_first_index).click();
                  if (tr_index == trs.length - 1) {
          
   
                      trs.eq(0).find(td).eq(td_first_index).click();
                  }
             }
             setTimeout(function() {
          
    $(.layui-table-edit).select() }, 0);
             break;
        case 37: //左
             td.prevAll([data-edit="text"]:first).click();
             setTimeout(function() {
          
    $(.layui-table-edit).select() }, 0);
             break;
        case 38: //上
            tr.prev().find(td).eq(td_index).click();
            setTimeout(function() {
          
    $(.layui-table-edit).select() }, 0);
            break;
        case 40: //下
            tr.next().find(td).eq(td_index).click();
            setTimeout(function() {
          
    $(.layui-table-edit).select() }, 0);
            break;
        
     }
});
经验分享 程序员 微信小程序 职场和发展