【问题标题】:Why does the ".id" method not work in this jQuery code?为什么“.id”方法在这个 jQuery 代码中不起作用?
【发布时间】:2017-05-09 17:33:17
【问题描述】:

我有以下几点:

var thisTable = $(this).closest('table').id;

萤火虫表演:

$(this).closest('table').id -> Undefined

但是,以下方法确实有效:

$(this).closest('table').attr('id')  -> "myTable"
$(this).closest('table').prop('id')  -> "myTable"

jQuery 的 .closest 等选择器后不支持 .id 方法吗?

【问题讨论】:

标签: jquery


【解决方案1】:

.id 不是方法,而是属性。 jQuery没有,js有。所以你需要做$(this).closest('table')[0]来获取js对象,而不是$(this).closest('table')[0].id

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="id-of-tbl">
  <tr>
    <td><button onClick="console.log($(this).closest('table')[0].id)">Get ID</button></td>
  </tr>
</table>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多