如何使用Jquery获取自定义属性

Rob*_*ght 7 forms checkbox jquery custom-attributes

在这种情况下,我们在复选框上有一个自定义属性,名为data-ref.

如何获得价值.这没用.

this.attr('data-ref');
Run Code Online (Sandbox Code Playgroud)

有任何想法吗,

奇妙

Dav*_*mas 18

您是否知道文本中的自定义属性"date-ref"和jQuery中的"data-ref"之间存在差异?

此外,您可能会发现使用jQuery对象更容易:

$(this).attr('data-ref');
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.

实际上,问题似乎是你没有使用jQuery对象:

this.attr('data-ref');
Run Code Online (Sandbox Code Playgroud)

无法工作

另一方面,要data-*使用DOM 检索属性,您可以选择:

this.getAttribute('data-ref');
Run Code Online (Sandbox Code Playgroud)

要么:

this.dataset.ref;
Run Code Online (Sandbox Code Playgroud)

要么:

this.dataset['ref'];
Run Code Online (Sandbox Code Playgroud)