Adding functionality for using the up and down arrow keys to select a table row

后端 未结 4 2205
甜味超标
甜味超标 2021-02-10 15:17

I need the help of an expert on my question below as it exceed and goes well beyond the level of knowledge that I have for programming in JavaScript.

Given the existing

4条回答
  •  梦谈多话
    2021-02-10 16:02

    I have create a demo using JQuery here on JSBin

    In general, we have 2 task:

    • highlight selected row
    • choose next/prev row

    To highlight the "clicked" row, I use this code

    $("#mstrTable tr").click(function(evt){
       var element = $(evt.target);
       var tableElement = element.parents('table');
       tableElement.find('tr').removeClass('highlighted');
       element.parents('tr').addClass('highlighted');
    });
    

    To choose next/prev row, I use jQuery tree traversal function with some exception when there is no tr inside your tbody. Note that keyCode of left, right, up, down arrow are 37, 39, 38, 40 respectively.

    $(document).keypress(function(evt){
              var highlightedRow = $("#mstrTable .highlighted");
              if (highlightedRow.length > 0) // table cell is selected
              {
                var tbodyElement = highlightedRow.parents('tbody');
                var trElements = tbodyElement.find('tr');
                var nextElement =  highlightedRow.next('tr');
                var prevElement = highlightedRow.prev('tr');
                trElements.removeClass("highlighted");
                switch(evt.keyCode)
                {
                  case 40:
                    if(nextElement.length)
                    {
                      nextElement.addClass('highlighted');
                    }
                    else if (trElements.length)
                    {
                      $(trElements[0]).addClass('highlighted'); 
                    }
                    break;
                  case 38:
                    if(prevElement.length)
                    {
                      prevElement.addClass('highlighted');
                    }
                    else if (trElements.length)
                    {
                      $(trElements[trElements.length - 1]).addClass('highlighted'); 
                    }
                    break;
                }
              }
            });
    

提交回复
热议问题