簡體   English   中英

jQuery:獲取數據屬性

[英]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中),但是,我嘗試了一下。
它奏效了!

有人可以解釋為什么嗎?

您可以使用.attr()函數:

$(this).attr('data-fullText')

或如果您將屬性名稱小寫

data-fulltext="This is a span element"

那么您可以使用.data()函數:

$(this).data('fulltext')

.data()函數應使用小寫屬性名稱,並且只能與小寫屬性名稱一起使用。

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

演示2: http //jsfiddle.net/hsakapandit/Jn4V3/1/

這對我有用

$('.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM