I'm using this code to add class for list items:
我正在使用此代码为列表项添加类:
jQuery('#news ul > li:first-child').addClass('first');
jQuery('#news ul > li:last-child').addClass('last');
It's working very well. The problem is when I have only one item...the code is adding the two classes for the same li.
它工作得很好。问题是当我只有一个项目时...代码是为同一个li添加两个类。
Example:
例:
-
Works perfectly if exist two or more items:
如果存在两个或更多项目,则完美地工作
<div id="nav"> <ul> <li class="first">Item 1</li> <li class="last">Item 2</li> </ul> </div>
-
Add the two classes for the unique item:
为唯一项添加两个类:
<div id="nav"> <ul> <li class="first last">Item 1</li> </ul> </div>
Is there a way to disable .last class if is only one item?
有没有办法禁用.last类,如果只有一个项目?
Thanks!
谢谢!
3 个解决方案
#1
3
Take a look at the :only-child
selector:
看一下:only-child选择器:
$('#news ul > li:last').not(':only-child').addClass('last');
#2
4
$('#news ul > li:first').addClass('first');
$('#news ul > li:last').not('.first').addClass('last');
#3
4
why not just handle this with CSS?
为什么不用CSS处理这个?
#news ul > li.last { }
#news ul > li.first,
#news ul > li.first.last { }
#1
3
Take a look at the :only-child
selector:
看一下:only-child选择器:
$('#news ul > li:last').not(':only-child').addClass('last');
#2
4
$('#news ul > li:first').addClass('first');
$('#news ul > li:last').not('.first').addClass('last');
#3
4
why not just handle this with CSS?
为什么不用CSS处理这个?
#news ul > li.last { }
#news ul > li.first,
#news ul > li.first.last { }