1

How can i get the data attribute of the last table row?

<tbody id="tableNotifications">
    <tr class="notificationsRowEntry success" data-notification-timestamp="1384105387"></tr>
    <tr class="notificationsRowEntry success" data-notification-timestamp="1384105367"></tr>
    <tr class="notificationsRowEntry success" data-notification-timestamp="1384105357"></tr>
    <tr class="notificationsRowEntry success" data-notification-timestamp="1384105323"></tr>
</tbody>

The problem is that i can't get the data attribute but only the content of the last table row using:

$data = $("#tableNotifications").last().data("notification-timestamp");

Maybe i'm doing a stupid mistake but it's driving me crazy.

Thank you.

P.S. I know that i could add some unique ids and then fetch the data with

 $data = $(uniqueid).data("notification-timestamp");

but i would like to avoid that.

4

3 回答 3

3

您想获取 data 属性的值tr,而不是tbody本身:

$("#tableNotifications > tr:last-child").data("notification-timestamp");
于 2013-11-10T19:50:48.097 回答
3

使用attr()功能:

var data = $("#tableNotifications tr:last").attr("data-notification-timestamp");

选择器#tableNotifications tr:last选择last trid 元素的子元素tableNotifications

这也将起作用:

var data = $("#tableNotifications tr").last().attr("data-notification-timestamp");

只是为了澄清:

如果您只想从 HTML 中获取属性值,请使用.attr("data-attr"). 有关更多信息,请参阅之间的区别.data().attr()

于 2013-11-10T19:52:36.270 回答
3

那就是找到 ID 为“tableNotifications”的最后一个元素。只需附加tr到您的选择器即可获得最后一行:

$data = $("#tableNotifications tr").last().data("notification-timestamp");
于 2013-11-10T19:58:18.290 回答