如何选择jQuery中的最后一个子元素?

如何选择jQuery中的最后一个子元素?

只是最后一个孩子,而不是其后代。


摇曳的蔷薇
浏览 434回答 3
3回答

湖上湖

您也可以这样做:<ul id="example">&nbsp; &nbsp; <li>First</li>&nbsp; &nbsp; <li>Second</li>&nbsp; &nbsp; <li>Third</li>&nbsp; &nbsp; <li>Fourth</li></ul>// possibility 1$('#example li:last').val();// possibility 2$('#example').children().last()// possibility 3$('#example li:last-child').val();

饮歌长啸

对于性能:$('#example').children().last()或者,如果您想让最后一个孩子上一堂课,如上所述。$('#example').children('.test').last()或具有特定类别的特定子元素$('#example').children('li.test').last()

牧羊人nacy

如果要选择最后一个子元素,并且需要具体说明元素类型,则可以使用选择器last-of-type这是一个例子:$("div p:last-of-type").css("border", "3px solid red");$("div span:last-of-type").css("border", "3px solid red");<div id="example">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>This is paragraph 1</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>This is paragraph 2</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span>This is paragraph 3</span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span>This is paragraph 4</span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>This is paragraph 5</p>&nbsp; &nbsp; &nbsp; &nbsp; </div>在上面的示例中,第4款和第5款都将带有红色边框,因为第5款是div中“ p”类型的最后一个元素,而第4款是div中的最后“ span”。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JQuery