javascript - jQuery - element.on 点击​​匹配案例

标签 javascript jquery html

我有一个元素位于某个表内。 我需要获取他的 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/

相关文章:

javascript - 如何为 ajax 响应在每个表行输出 3 个单元格 (<td> </td>)?

javascript - 原始 html 渲染与动态 JS 渲染的间距不同

javascript - 在文本框中显示增值税值

javascript - 将当前链接设置为事件链接

html - 从所有类型的 li 和 ul 中删除黑点

javascript - 嵌入 YouTube 视频 : Custom Javascript Actions on Thumbnail

javascript - 水平网站上的 scrollTop 或 scrollLeft?

php - ExtJS 4 - 从超链接加载网格

javascript - 两种方式的数据绑定(bind)不适用于 Kendo UI

jquery - 使用 Bootstrap Dropdown - 通过 Jquery 聚焦输入