在我的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'));
});
然后我搜索并找到了这些问题:How to get the data-id attribute?和jquery can't get data attribute value。
两者的答案都是"Use .attr('data-sth') or .data('sth')"
。
我知道.attr()
已被弃用(在我使用的jquery-1.11.0中),但我还是尝试了一下。
它成功了!
有人能解释一下原因吗?
发布于 2016-08-20 15:16:39
您可以随意更改ID和数据属性!
<select id="selectVehicle">
<option value="1" data-year="2011">Mazda</option>
<option value="2" data-year="2015">Honda</option>
<option value="3" data-year="2008">Mercedes</option>
<option value="4" data-year="2005">Toyota</option>
</select>
$("#selectVehicle").change(function () {
alert($(this).find(':selected').data("year"));
});
下面是一个工作示例:https://jsfiddle.net/ed5axgvk/1/
发布于 2015-04-26 23:06:43
这对我很管用
$('.someclass').click(function() {
$varName = $(this).data('fulltext');
console.log($varName);
});
发布于 2017-09-23 16:50:30
这是我想出来的:
$(document).ready(function(){
$(".fc-event").each(function(){
console.log(this.attributes['data'].nodeValue)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id='external-events'>
<h4>Booking</h4>
<div class='fc-event' data='00:30:00' >30 Mins</div>
<div class='fc-event' data='00:45:00' >45 Mins</div>
</div>
https://stackoverflow.com/questions/23592030
复制相似问题