使用 jQuery 获取我自己的属性数据

Get my own attribute's data with jQuery

我使用 jQuery 动态构建一个 .因为稍后我需要捕获 table 单元格上的双击事件,并且我需要确切地知道(双击)了哪一行和哪一列,所以我在每一行和每列,即:

<tr data-tr-number="2">
    <td data-td-number="1">John</td>
    <td data-td-number="2">Due</td>
    <td data-td-number="3">U.S.A.</td>
</tr>

现在,当我稍后尝试获取这些属性的值(以及元素的 html 值)时,出现错误。我究竟做错了什么?

谢谢

this.attr("data-td-number")   --->   Uncaught TypeError: undefined is not a function

同样适用于:

this.html    or     this.closest("tr").attr("data-tr-number")

问题是 this 指向 HTMLTableCellElement 对象,而不是 jQuery 实例对象。所以你不能在上面使用 attr 方法。而是使用:

$(this).attr("data-td-number") 

您可以轻松验证:

console.log(this instanceof HTMLTableCellElement); // true
console.log($(this) instanceof jQuery); // true

您始终可以将纯 HTML 元素包装到 jQuery 函数中,以使用 attrclosest 等所有必要方法构造 jQuery 的新实例等

或者你也可以这样做。

$(this).data("td-number")