如何使用jQuery获取仅包含隐藏div的表格<tr>元素
获取表格中仅包含隐藏div的元素(jQuery实现)
我有一个包含多个<tr>的表格,部分<td>里有隐藏的div,其他<tr>里有显示状态的div。点击按钮时,我想获取所有仅包含隐藏div的<tr>,请问怎么用jQuery实现?我之前写了一段代码能正确获取这类元素的数量,但现在需要拿到完整的<tr>数据。
尝试的代码
$('div[id*="addDiv"]').filter(function() { return $(this).css('display') !== 'none'; }).length;
对应的HTML代码
<table class="table"> <thead> <tr> <th scope="col">Student Name</th> <th scope="col">Student Email</th> <th scope="col">Parent Phone</th> <th scope="col">Actions</th> </tr> </thead> <tbody> <tr id="tr<?php echo $en->id; ?>"> <td><?php echo $en->fullname; ?> </td> <td><?php echo $en->email; ?></td> <td id="phone<?php echo $en->id; ?>"><?php echo $parentPhone; ?></td> <td> <div id="addDiv<?php echo $en->id; ?>" <?php if ($parentPhone != "-") { echo "style='display:none;'"; } ?>> <button id='add<?php echo $en->id; ?>' data-toggle='modal' class='fired2 btn btn-primary' data-toggle='addModal' data-target='#addModal' data-id='<?php echo $en->id; ?>'>Add Parent</button> </div> <div id="editDiv<?php echo $en->id; ?>" <?php if ($parentPhone == "-") { echo "style='display:none;'"; } ?>> <button data-toggle='modal' class='btn btn-success fired' data-toggle='editModal' data-target='#editModal' data-id='<?php echo $en->id; ?>' data-fname='<?php echo $userParent->firstname; ?>' data-lname='<?php echo $userParent->lastname; ?>' data-phone='<?php echo $userParent->phone1; ?>' data-email='<?php echo $userParent->email; ?>' id='edit<?php echo $en->id; ?>'>Edit Parent</button> <button type='button' data-id='<?php echo $en->id; ?>' id='war<?php echo $en->id; ?>' class='btn btn-outline-warning'>Delete Parent</button> </div> <button type="button" data-id="<?php echo $en->id; ?>" id="dang<?php echo $en->id; ?>" class="btn btn-outline-danger">Unenrol student from the course</button> </td> </tr> </tbody> </table>
解决方案
要获取所有仅包含隐藏div的<tr>,可以通过以下jQuery代码实现:
// 绑定按钮点击事件 $('button').click(function() { // 筛选出所有符合条件的tr元素 const targetTrs = $('tbody tr').filter(function() { // 检查当前tr内的addDiv和editDiv是否均处于隐藏状态 const isAddHidden = $(this).find('div[id*="addDiv"]').is(':hidden'); const isEditHidden = $(this).find('div[id*="editDiv"]').is(':hidden'); return isAddHidden && isEditHidden; }); // 操作筛选后的tr集合 console.log('符合条件的tr数量:', targetTrs.length); // 遍历获取每个tr的具体数据示例 targetTrs.each(function(idx, tr) { const studentName = $(tr).find('td:first').text().trim(); const studentEmail = $(tr).find('td:nth-child(2)').text().trim(); console.log(`第${idx+1}条数据:姓名-${studentName},邮箱-${studentEmail}`); }); });
代码说明
- 用
$('tbody tr')精准定位表格数据行,避免选中表头行 - 使用
:hidden选择器判断元素是否隐藏,比读取css('display')更可靠,能覆盖visibility: hidden、父元素隐藏等多种隐藏场景 - 筛选完成后,
targetTrs是jQuery对象集合,可直接调用.length获取数量,或用.each()遍历处理每个<tr>的内容
内容的提问来源于stack exchange,提问作者drive1 drive2
相关产品推荐
相关产品推荐

