javascript - 有没有办法使用 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>
解决方案
您的代码中的问题是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>
推荐阅读
- python - 通过设置或 Python LibVLC API 对 VLC 网络流中的自动重新连接失败进行故障排除
- html - div标签中的背景图像大小 - 全屏 - 内联css
- android - 如何检查应用程序是否使用 jni 安装?
- ajax - 阿贾克斯和 Django
- java - 如何在不使用数组的情况下更改 showConfirmDialog 中的文本?
- reactjs - 如何从 Redux store 中删除 Board-React js,redux
- javascript - PHP 联系表格未收到电子邮件但已确认
- anaconda - 在 Anaconda 问题上安装 pymzml
- javascript - 由于 ble.scan 的异步执行,基于设备名称的 Cordova BLE Connect 自动(无需用户操作)失败
- java - IntelliJ IDEA:java.lang.ClassNotFoundException:com.mysql.jdbc.Driver