[英]jQuery: get data attribute
在我的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中),但是,我嘗試了一下。
它奏效了!
有人可以解釋為什么嗎?
1.試試這個: .attr()
$('.field').hover(function () {
var value=$(this).attr('data-fullText');
$(this).html(value);
});
演示1: http : //jsfiddle.net/hsakapandit/Jn4V3/
2.試試這個: .data()
$('.field').hover(function () {
var value=$(this).data('fulltext');
$(this).html(value);
});
這對我有用
$('.someclass').click(function() {
$varName = $(this).data('fulltext');
console.log($varName);
});
根據需要更改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/
這是我想出的:
$(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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.