JQuery - 如何向每个最后一个列表项添加一个类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/563740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery - How to add a class to every last list item?
提问by Keith Donegan
Got some code here that isn't working:
这里有一些不起作用的代码:
$("#sidebar ul li:last").each(function(){
$(this).addClass("last");
});
Basically I have 3 lists and want to add a class (last) to each item appearing last in each unordered list.
基本上我有 3 个列表,并且想为每个无序列表中最后出现的每个项目添加一个类(最后一个)。
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li class="last">Item 3</li>
</ul>
Hope that makes sense, Cheers!
希望这是有道理的,干杯!
回答by cletus
Easy mistake to make. Try this:
容易犯错。尝试这个:
$("#sidebar ul li:last-child").addClass("last");
Basically :last doesn't quite do what you think it does. It only matches the very last in the document, not the last in each list. That's what :last-child is for.
基本上 :last 并没有完全按照你的想法去做。它只匹配文档中的最后一个,而不是每个列表中的最后一个。这就是 :last-child 的用途。
回答by Ayham
with jquery add this
用 jquery 添加这个
$("ul li").last().addClass('last');
回答by cdmckay
The reason that won't work is due to the fact that :last
only matches one element. From the jQuery documentation:
不起作用的原因是因为:last
只匹配一个元素。来自 jQuery 文档:
Matches the last selected element.
匹配最后一个选定的元素。
So what your code is doing is getting a set of all the <li>
elements in a <ul>
and then from that set taking the last value. Example:
所以你的代码正在做的是获取 a 中所有<li>
元素的集合,<ul>
然后从该集合中获取最后一个值。例子:
<ul>
<li>1</li>
<li>2</li>
</ul>
<ul>
<li>3</li>
<li>4</li>
</ul>
<ul>
<li>5</li>
<li>6</li>
</ul>
Your code would return the element <li>6</li>
. (Internally, it'd collect <li>1</li>
to <li>6</li>
and then lop off the last one and return it).
您的代码将返回元素<li>6</li>
。(在内部,它会收集<li>1</li>
到<li>6</li>
最后一个然后将其砍掉并返回)。
What you're looking for is what the other answers here have said: :last-child
.
您正在寻找的是此处其他答案所说的内容::last-child
。
回答by cdmckay
Or you could give your list an id and use that as an context to jquery-call.
或者你可以给你的列表一个 id 并将其用作 jquery-call 的上下文。
<ul id="myList">
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>
<ul id="anotherList">
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>
And then you can do:
然后你可以这样做:
jQuery("li:last", "ul#myList").addClass("lastItem");
Now the last li in the first list would have class "lastItem".
现在第一个列表中的最后一个 li 将具有类“lastItem”。
Edit: Sorry, misread the question. Ignore this please.
编辑:对不起,误读了这个问题。请忽略这一点。
回答by Burning
If you need to add class to 3 separate lists you can assign a class for them and use 'each':
如果您需要将类添加到 3 个单独的列表中,您可以为它们分配一个类并使用“每个”:
$('#sidebar ul.class li:last-child').each(function(e){
$(this).addClass("last");
});
This should work exactly as you expected.
这应该完全按照您的预期工作。
回答by smoothdeveloper
you can try
你可以试试
$('#sidebar ul li:last').addClass('last');