从this SO question中获取提示,我采用了类似的方法,使用jQuery的.closest()
方法来定位元素。
<tr class="open"><td colspan="3">When 1 is clicked, target this tr</td></tr>
<tr>
<td colspan="3">
<table>
<tbody>
<tr>
<td class="first-level">1</td> <!-- Click 1 -->
<td>Some label</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr class="open"><td colspan="3">When 2 is clicked, target this tr</td></tr>
<tr>
<td colspan="3">
<table>
<tbody>
<tr>
<td class="first-level">2</td> <!-- Click 2 -->
<td>Some label</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr class="open"><td colspan="3">When 3 is clicked, target this tr</td></tr>
<tr>
<td colspan="3">
<table>
<tbody>
<tr>
<td class="first-level">3</td> <!-- Click 3 -->
<td>Some label</td>
</tr>
</tbody>
</table>
</td>
</tr>
$('#example tbody').on('click', 'td.first-level', function () {
var tr = $(this).closest('.open'); // this is returning empty
});
编辑:我无法使用colspan
属性来遍历DOM,因为有时它甚至可能不存在。
因此,出于演示目的,我们假设用户点击了包含2的td
。因此,在这种情况下,选择适当的tr
的方法是什么?
答案 0 :(得分:3)
您需要使用:
$(this).closest('td[colspan="3"]').parent().prev();
或
$(this).closest('table').closest('tr').prev();
<强> Working Demo 强>
使用顶级父表:
$(this).closest('#example').find('.open');
<强> Working Demo 强>