Help with JQuery selector :not(:last)

2019-04-03 06:32发布

问题:

I'm trying to select all the bullets except the last bullet but I am doing something incorrectly.

Here is my html

<ul>
<li>Text</li>
<li>Text</li>
<li>Text</li>
<li>Text</li>
<li>Text</li>
</ul>

<ul>
<li>Text</li>
<li>Text</li>
<li>Text</li>
<li>Text</li>
<li>Text</li>
</ul>


<ul>
<li>Text</li>
<li>Text</li>
<li>Text</li>
<li>Text</li>
<li>Text</li>
</ul>

And my jQuery:

jQuery('ul li:not(:last)').append(" | ");

It's adding the pipe to every bullet however...

回答1:

Because your html contains multiple unordered lists, $('ul li') will selects every single <li>, in all of the <ul>s. :last then selects the final element in that list. Use :last-child, which gets the last <li> in each of the <ul>s.

$('ul li:not(:last-child)').append(' | ');

http://jsfiddle.net/mattball/qmVdb/1/