首页 > 解决方案 > 如何使子行列可点击?

问题描述

我有一个 HTML 表,其中有子行,我想让这些子行列可单击以执行特定操作。

我有父行,当我单击这些行时,将显示子行,其中有一个 column col2,当我单击它时,它应该对每个子行列执行一些操作。

我希望col2子行可以点击以使用 JavaScript 和 HTML 显示更多信息。我不知道,但是在点击功能(onclick('col2'))上,类似的东西是否有帮助?

var $container = $("#container");
var $row = $("#container table tbody tr");

// Loop through items in JSON data..
var $button = $("<button>" + 'abc' + "</button>");
$container.prepend($button);
var table = $("<table>");
table.append($("<tr><th>col1</th><th>col2</th></tr>"));

// Button click handler..
$button.on("click", function() {
  for (var i = 0; i < 2; i++) {

    // Replace row HTML..
    //parent row
    var row = $('<tr class="parent_row" ><td>' + 'data' + '</td>' + +'<td>' + "" + '</td></tr>');

    table.append(row);

    for (var j = 0; j < 2; j++) {
      //child row
      var row = $('<tr style="display: none"><td>' + "" + '</td>' + '<td>' + 'data' + '</td></tr>');
      table.append(row);
    }
  }

  $("#table").html(table);
  $('.parent_row').click(function() {

    $(this).nextUntil(".parent_row").toggle();
  })
  // Show table if it's not already visible..


});
table {
  margin-top: 20px;
  border: 1px solid silver;
  width: 500px;
}

th {
  text-align: left;
}

button {
  margin-left: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <div id="table">
  </div>

</div>

标签: javascripthtml

解决方案


要捕获对表格中任何列的点击,只需向该列中的所有单元格添加一个点击侦听器:

const column2cells = document.querySelectorAll('#table tr>*:nth-child(2)');

for (const cell of column2cells) {
  cell.addEventListener('click', function(event) {
    console.log(`You clicked cell [${cell.cellIndex}, ${cell.parentElement.rowIndex}] with content "${cell.textContent}"`);
  })
}
<table id="table">
    <tr>
      <th>Col 1</th>
      <th>Col 2</th>
    </tr>
    <tr>
      <td>Col 1</td>
      <td>Col 2</td>
    </tr>
    <tr>
      <td>Col 1</td>
      <td>Col 2</td>
    </tr>
</table>

作为日志输出的注释:记住cellIndexrowIndex从 开始0,而不是在1


推荐阅读