jQuery:获取数据属性 [英] jQuery: get data attribute

查看:88
本文介绍了jQuery:获取数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的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 属性。我尝试了这两种方法,但它们没有用(两者都返回未定义):

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无法获取数据属性值

这两个答案都是使用。 attr('data-sth')或.data('sth')

我知道 .attr()已被弃用(在我使用的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!

有人可以解释原因吗?

推荐答案

你可以使用 .attr() 功能:

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() function expect和仅适用于小写属性名称。

The .data() function expects and works only with lowercase attribute names.

这篇关于jQuery:获取数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆