使用 JQuery 时使用“:last-of-type”或“.last()”
":last-of-type" or ".last()" when using JQuery
:last-of-type (as of v1.9) vs .last() (as of v1.4): 两种方法都可以,但是谁能告诉我哪种方法效率更好?
示例:
$(".item").last();
$(".item:last-of-type");
".last()" 存在时间更长(从 v1.4 开始)。
JQuery 是否内置了“:last-of-type”,或者它只是利用 CSS 并搭载浏览器的功能?谁能证实这一点?
在我看来,如果是这种情况,“:last-of-type”在适用时会更好。
.last()
更快。
注意,选择器执行不同的选择
last-of-type selector
Description: Selects all elements that are the last among siblings of
the same element name.
.last()
Description: Reduce the set of matched elements to the final one in
the set.
console.time("lastOfType");
$(".item:last-of-type");
console.timeEnd("lastOfType");
console.time("last");
$(".item").last();
console.timeEnd("last");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
:last-of-type (as of v1.9) vs .last() (as of v1.4): 两种方法都可以,但是谁能告诉我哪种方法效率更好?
示例:
$(".item").last();
$(".item:last-of-type");
".last()" 存在时间更长(从 v1.4 开始)。 JQuery 是否内置了“:last-of-type”,或者它只是利用 CSS 并搭载浏览器的功能?谁能证实这一点?
在我看来,如果是这种情况,“:last-of-type”在适用时会更好。
.last()
更快。
注意,选择器执行不同的选择
last-of-type selector
Description: Selects all elements that are the last among siblings of the same element name.
.last()
Description: Reduce the set of matched elements to the final one in the set.
console.time("lastOfType");
$(".item:last-of-type");
console.timeEnd("lastOfType");
console.time("last");
$(".item").last();
console.timeEnd("last");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>