我想通過數據屬性值(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錯誤,但?
有在您提供的html中沒有data-event_id屬性。請更新您的示例代碼。 –
'.find()'永遠不會返回'undefined',即使它沒有找到任何東西,它也會返回一個空的jQuery集合。 – Barmar
[jQuery如何找到基於數據屬性值的元素的可能的重複?](http://stackoverflow.com/questions/4191386/jquery-how-to-find-an-element-based-on-a -data-attribute-value) – showdev