首页 > 解决方案 > 有没有办法使用 jQuery 查找任何表的行数?

问题描述

我在我的网页上设置了各种 HTML 表格,并希望找到一种方法来了解它们在 jQuery 中包含的行数,而无需在表格中使用类或 id。这可能吗?

我已经尝试将 HTML 按钮与单击事件处理程序链接起来,以获取最近的表格并计算其长度,但我似乎在这里做错了。

我想找到任何表格的长度,以便能够更改按钮的操作,具体取决于表格中剩余的行数。

1每当我在任何大小的表上尝试时,rowCount 的实际输出都是。

$(document).on("click", "button.x-cross", function() {
  var rowCount = $(this).closest("table >tr").length;

  // Conditions using the rowCount variable

  return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <span>First row</span>
    </td>
    <td>
      <button type="button" class="x-cross">X</button>
    </td>
  </tr>
</table>

标签: javascriptjqueryhtml

解决方案


您的代码中的问题是table是最接近按钮的父元素,而不是table > tr,因此该选择器找不到任何东西。如果将选择器分隔为closest()and then find(),则可以:

$(document).on("click", "button.x-cross", function() {
  var rowCount = $(this).closest("table").find('tr').length;
  console.log(rowCount);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <span>First row</span>
    </td>
    <td>
      <button type="button" class="x-cross">X</button>
    </td>
  </tr>
</table>

<table>
  <tr>
    <td>
      <span>First row</span>
    </td>
  </tr>
  <tr>
    <td>
      <span>Second row</span>
    </td>
  </tr>
  <tr>
    <td>
      <span>Third row</span>
    </td>
    <td>
      <button type="button" class="x-cross">X</button>
    </td>
  </tr>
</table>


推荐阅读