代码之家  ›  专栏  ›  技术社区  ›  Penny Liu

选择表单元格作为组

  •  2
  • Penny Liu  · 技术社区  · 7 年前

    在此表中,我要选择多个单元格作为一个组。 你可以点击一个目标单元格, 但我也想 点击并拖动 一组覆盖多个单元格。

    不需要任何插件(只使用jquery)就可以实现吗?

    这就是我想要实现的:

    enter image description here

    数组内容将是: ["3-2", "3-3", "4-2", "4-3", "5-2", "5-3"]

    以下是我目前所做的尝试:

    var group = [];
    
    var columnIndex = 7,
      rowIndex = 10;
    var $tableContainer = $('#tablecontainer'),
      $table = $tableContainer.append('<table border="1" id="table1"></table>'),
      $thead = $table.find('table').append('<thead></thead>'),
      $tbody = $table.find('table').append('<tbody></tbody>');
    
    var $columnNumber = "";
    var $tdNumber = "";
    for (var col = 1; col <= columnIndex; col++) {
      $columnNumber += "<th>Column " + col + "</th>";
      $tdNumber += "<td style='text-align: center; vertical-align: middle; color:red'></td>";
    }
    
    $thead = $thead.append('<tr><th>0</th>' + $columnNumber + '</tr>');
    
    for (var row = 1; row <= rowIndex; row++) {
      $tbody = $tbody.append('<tr><td>Row ' + row + '</td>' + $tdNumber + '</tr>');
    }
    
    $('#table1 > tbody > tr >  td').hover(function() {
      var colIndex = $(this).parent().children().index($(this));
      var rowIndex = $(this).parent().parent().children().index($(this).parent());
      $(this).attr("title", 'Row: ' + rowIndex + ', Column: ' + colIndex);
      // console.log('Row: ' + rowIndex + ', Column: ' + colIndex);
    });
    
    $('#table1 > tbody > tr >  td').click(function() {
      var colIndex = $(this).parent().children().index($(this));
      var rowIndex = $(this).parent().parent().children().index($(this).parent());
      group.push(rowIndex + "-" + colIndex);
      console.log(group);
      $(this).css("background-color", "red");
      // console.log('Row: ' + rowIndex + ', Column: ' + colIndex);
    });
    #table1>tbody>tr>td:hover {
      background: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="tablecontainer"></div>

    任何帮助都将不胜感激!

    1 回复  |  直到 7 年前
        1
  •  3
  •   Help    7 年前

    通过使用 jquery mouseover 功能。 我做了一把小提琴以获得你所期望的输出。

    Fiddle

    希望这能帮助你解决这个问题。

    -帮助:)