您好,欢迎访问一九零五行业门户网

jquery选择器 :last与:last-child两者的区别

今天写$(ul li:last-child).offset().top发现报错,而$(ul li).last().offset().top就没错了。原因在于:
这两个选择器都是匹配集合中的最后一个元素,差别在于 :last 将匹配所有的集合中的最后一个元素。而 :last-child 将匹配集合中的所有位置为最后一个的子元素。:last 将永远返回一个元素,而 :last-child可能返回一批元素。
原来如此啊!
:last selects the last matched element. note that :last selects a single element by filtering the current jquery collection and matching the last element within it. additional notes: because :last is a jquery extension and not part of the css specification, queries using :last cannot take advantage of the performance boost provided by the native dom queryselectorall() method. to achieve the best performance when using :last to select elements, first select the elements using a pure css selector, then use.filter(":last").
:last-child:
selects all elements that are the last child of their parent.
<div> <span>john,</span> <span>karl,</span> <span>brandon,</span> <span>sam</span> </div> <div> <span>glen,</span> <span>tane,</span> <span>ralph,</span> <span>david</span> </div> <script> $("div span:last-child") .css({color:"red", fontsize:"80%"}) .hover(function () { $(this).addclass("solast"); }, function () { $(this).removeclass("solast"); });
这两个选择器都是匹配集合中的最后一个元素,差别在于 :last 将匹配所有的集合中的最后一个元素。而 :last-child 将匹配集合中的所有位置为最后一个的子元素。:last 将永远返回一个元素,而 :last-child可能返回一批元素。
$('div p:last') 选择最后一个p元素并高亮显示得出结果如下:
<div> <p>paragraph</p> <p>paragraph</p> <p>paragraph</p> </div> <div> <p>paragraph</p> <p>paragraph</p> <p>paragraph</p> </div> <div> <p>paragraph</p> <p>paragraph</p> <p>paragraph</p> </div>

$('div p:last-child') 将选择所有位于div最后一个p子元素,并高亮:
<div> <p>paragraph</p> <p>paragraph</p> <p>paragraph</p> </div> <div> <p>paragraph</p> <p>paragraph</p> <p>paragraph</p> </div> <div> <p>paragraph</p> <p>paragraph</p> <p>paragraph</p> </div>

以上就是jquery选择器 :last与:last-child两者的区别的详细内容。
其它类似信息

推荐信息