我有一个元素位于某个表内。 我需要获取他的 tbody 元素。
我该怎么做?
尝试过$(this).closest('tbody')
但是好像没用..
我的代码:
$("table").on('click', ['td'], function(event) {
if ($(this).hasClass('uneditable')) { return; }
// here I need to check the tbody element
console.log($(this).closest("tbody"))
}
也许我做错了,因为我只想在单击具有特定元素类的表格时应用此功能:
- 表 -
dattable
- tbody -
编辑
- td - 不是
uneditable
谢谢!
最佳答案
您应该使用 $("table").on('click', 'td',
而不 $("table").on ('点击', ['td'],
console.log($('#a1').closest('tbody').length)
$("table").on('click', 'td', function(event) {
if ($(this).hasClass('uneditable')) { return; }
// here I need to check the tbody element
console.log($(this).closest("tbody").length)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><div id="a1">asdf</div></td>
</tr>
</table>
通过使用 ['td']
- this
是对 table
的引用(而不是单元格 - td
), 所以你不能使用 closest
来找到 tbody
元素。
更新
如果您只想选择不具有特定类的td
,您可以使用:not
伪类:
$("table").on('click', 'td:not(.uneditable)', function(event) {
console.log($(this).closest("tbody").length)
});
.uneditable {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="t"><div>asdf</div></td>
</tr><tr>
<td class="uneditable"><div>asdf</div></td>
</tr><tr>
<td class="t"><div>asdf</div></td>
</tr>
</table>
关于javascript - jQuery - element.on 点击匹配案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40192702/