2014-02-06 188 views
0

我想通過數據屬性值(data-event_id = 1282)獲取<li>元素。jQuery通過數據ID獲取元素

<div id="timeline"> 
    <ul> 
     <li class="timeline-event"> 
      <div>Event Body</div> 
     </li> 
    </ul> 
</div> 

$el = $('#timeline ul').find("li.timeline-event").data('event_id'); 
console.log($el); // returns 1282 

$el = $('#timeline ul').find("li.timeline-event[data-event_id='1282']").html(); 
console.log($el); // returns undefined 

我在做什麼錯?

編輯 - 解

數據使用。數據集( 'event_id的', '1282')中的代碼的其他地方。

如果使用.data()設置jQuery,則無法獲取數據。

我在這裏找到了使用@ByData函數的解決方案@psycho brm。有用!

jQuery how to find an element based on a data-attribute value?

$.fn.filterByData = function(prop, val) { 
    return this.filter(
     function() { return $(this).data(prop)==val; } 
    ); 
} 

我想這一定是一個jQuery錯誤,但?

+2

有在您提供的html中沒有data-event_id屬性。請更新您的示例代碼。 –

+1

'.find()'永遠不會返回'undefined',即使它沒有找到任何東西,它也會返回一個空的jQuery集合。 – Barmar

+0

[jQuery如何找到基於數據屬性值的元素的可能的重複?](http://stackoverflow.com/questions/4191386/jquery-how-to-find-an-element-based-on-a -data-attribute-value) – showdev

回答

0

數據在代碼中的其他地方使用.data('event_id','1282')設置。

如果使用.data()設置jQuery,則無法獲取數據。

我在這裏找到了使用filterByData函數的解決方案。有用!

jQuery how to find an element based on a data-attribute value?

+0

在您的答案中添加您的參考答案的內容。否則你的答案只不過是一個沒有提升的鏈接而已。如果你提供小提琴會很好 – Satpal

0

我沒有在您的html中看到data-attr。

我曾嘗試與添加數據事項標識= 「1282」 李http://jsfiddle.net/dehisok/Wa5RG/

<li class="timeline-event" data-event_id="1282"> 

它的工作原理你的代碼!

+0

你如何解釋他的代碼的第一部分工作? – Barmar

+0

也許,之前有一些js代碼,它設置了「數據」(但不是屬性)。 –

0

第二證件回報不確定,因爲你應該爲他提供李 (I)類名兩個選項 (II)屬性

你應該嘗試指定只在他們的