有没有一种方法可以使用jQuery查找任何表的行数?

时间:2019-08-05 13:23:10

标签: javascript jquery html

我正在网页上建立各种HTML表格,并希望找到一种方法来知道每个表格在jQuery中包含的行数,而无需在表格中使用类或id。这可能吗?

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

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

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

$(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>

2 个答案:

答案 0 :(得分:3)

代码中的问题是table是最接近按钮的父元素,而不是table > tr,因此选择器什么都找不到。如果将选择器分别分为closest()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>

答案 1 :(得分:1)

您可以使用eq选择您选择的表格

console.log('First :' + $('table').eq(0).find('tr').length)
console.log('Second :' + $('table').eq(1).find('tr').length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1">
  <tr>
    <td>
      <span>First row</span>
    </td>
    <td>
     
    </td>
  </tr>
</table>

<table border="1">
  <tr>
    <td>
      <span>Second row</span>
    </td>
    <td>
     
    </td>
  </tr>
    <tr>
    <td>
      <span>Third row</span>
    </td>
    <td>
     
    </td>
  </tr>
</table>

相关问题