jQuery通过数据属性AND:last-child

时间:2018-10-04 10:38:26

标签: javascript jquery

希望对于其中的某些JS专家来说,这应该很简单!

好,所以我有各种<section>标签,它们具有data-week属性。每个部分还具有data-date属性。

在任何给定的一周内,我都需要按data-week分组以查看最后一部分,因此我可以检查日期是在本周早些时候还是将来。

当我这样做时,我得到2个结果:

let sections= $('section[data-week="' + thisWeek + '"]');

我只需要最后一个。我试图这样添加:last-child

let lastSectionOfThisWeek = $('section[data-week="' + thisWeek + '"]:last-child');

但这并没有返回任何东西。如何将两者一起使用以获取我的周号的最后一部分?

感谢您的帮助!

4 个答案:

答案 0 :(得分:3)

:last-child表示最后一个孩子,而不是也与选择器的其余部分匹配的最后一个孩子

给出:<a /><a /><b /><b />然后b:last-child将匹配最后一个b:last-child也将匹配,但是a:last-child将不匹配任何内容,因为两个{{ 1}}元素是最后一个子元素。

只需获取所有元素,然后pluck the last one off the set

a

或使用the jQuery-specific :last filter

let lastSectionOfThisWeek =  $('section[data-week="' + thisWeek + '"]').last();

答案 1 :(得分:2)

您可以使用.last()将匹配的元素集减少到集合中的最后一个元素:

let lastSectionOfThisWeek =  $('section[data-week="' + thisWeek + '"]:last');
let thisWeek = "1";

let lastSectionOfThisWeek = $('section[data-week="' + thisWeek + '"]').last();

console.log(lastSectionOfThisWeek.text().trim());

答案 2 :(得分:1)

使用:last选择器:

var thisWeek = "week";

console.log($(`section[data-week=${thisWeek}]:last`).attr("id")) // third
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="first" data-week="week">First</section>
<section id="second" data-week="week">Second</section>
<section id="third" data-week="week">Third</section>

答案 3 :(得分:0)

虽然节是数组,所以您可以通过这种方式获取最后一个值

let sections= $('section[data-week="' + thisWeek + '"]');
let lastsection= sections[sections.length-1];