问题
I have a group of <ul>
's created dynamically and i need a class added to the last <li>
of each one.
I have:
$('ul li:last').each(function(){
$(this).addClass("last");
});
But this only adds a class="last"
to the last <ul>
not in all of the <ul>
's.
I want the last <li>
of each <ul>
to get added the class, not just the last <ul>
.
回答1:
:last, a propriety jQuery selector, pops off the last element from the set and returns it.
:last-child, the CSS selector, selects the last child of each ancestor element.
$('ul li:last-child').addClass('last');
jsFiddle.
As a side note, you don't need to use each()
there. The addClass()
will be ran over each item in the jQuery set.
来源:https://stackoverflow.com/questions/9185361/add-class-to-the-last-li-in-a-group-of-ul