获取数据属性 [英] Get data attribute
问题描述
在我的html中,我有一个 span
元素:
In my html I have a span
element:
<span class="field" data-fullText="This is a span element">This is a</span>
我想获取 data-fullText
属性。我尝试了这两种方式,但它们都不起作用(两者都返回 undefined
):
And I want to get the data-fullText
attribute. I tried these two ways, but they didn't work (the both return undefined
):
$('.field').hover(function () {
console.log('using prop(): ' + $(this).prop('data-fullText'));
console.log('using data(): ' + $(this).data('fullText'));
});
然后我搜索并发现了这些问题:如何获取data-id属性?和 jquery无法获取数据属性值。
这两个答案都是Use。我知道
.attr()$ c $> c>已被弃用(在我使用的jquery-1.11.0中),但是,我试过了。
它工作正常!
Then I searched and found these questions: How to get the data-id attribute? and jquery can't get data attribute value.
The both's answers are "Use .attr('data-sth') or .data('sth')"
.
I know that .attr()
is deprecated (in jquery-1.11.0, which I use), but, however, I tried it.
And it workded!
有人可以解释为什么吗?
Can someone explain why?
推荐答案
You could use the .attr()
function:
$(this).attr('data-fullText')
或者小写属性名称:
data-fulltext="This is a span element"
然后您可以使用 .data()
函数:
then you could use the .data()
function:
$(this).data('fulltext')
.data()
函数只能使用小写属性名称。
The .data()
function expects and works only with lowercase attribute names.
这篇关于获取数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!