最佳答案
在 html 中,我有一个 span
元素:
<span class="field" data-fullText="This is a span element">This is a</span>
我想得到 data-fullText
属性。我试过这两种方法,但都不管用(两种方法都返回 undefined
) :
$('.field').hover(function () {
console.log('using prop(): ' + $(this).prop('data-fullText'));
console.log('using data(): ' + $(this).data('fullText'));
});
然后我搜索并找到了这些问题: 如何获取 data-id 属性?和 Jquery 不能得到数据属性值。
这两个问题的答案都是 "Use .attr('data-sth') or .data('sth')"
。
我知道 .attr()
是不推荐的(在我使用的 jquery-1.11.0中) ,但是,我还是尝试了。
成功了!
有人能解释一下为什么吗?