在我的html中,我有一个span元素:

<span class="field" data-fullText="This is a span element">This is a</span>

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'));
});

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"

then you could use the .data() function:

$(this).data('fulltext')

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

Jquery相关问答推荐

如何定位 prism.js 脚本中包含的代码?

通过 jQuery 提取 application/json 数据

如何使用 aria-expanded="true" 更改 CSS 属性

提醒未保存的表单更改

jQuery ajax 调用默认超时值

Google Maps API v3 infowindow 关闭事件/回调?

为什么 jquery fadeIn() 不能与 .html() 一起使用?

如何使用 JQuery 发布 JSON 数据?

删除所有子元素的 CLASS

在没有 jQuery 的情况下在 node.js 上合并或合并 JSON

javascript 正则表达式用于包含至少 8 个字符、1 个数字、1 个大写和 1 个小写的密码

字符串化(转换为 JSON)具有循环引用的 JavaScript 对象

判断元素是否为 div

JavaScript:让代码每分钟运行一次

Rails 无法正确解码来自 jQuery 的 JSON(数组变成带有整数键的散列)

如何从所有元素jquery中删除类

如何在文件 Select 上触发事件

将变量的值复制到另一个

jQuery,简单的轮询示例

jQuery 将换行符转换为 br (nl2br 等效)