我有一个相当标准的UL,我试图一次三个一组地循环通过孩子LI,但是我很难让选择器正确选择nth-child然后是下一个两个兄妹李。
我在想像......
var start_index = 1; //start with the first <li>
$("li:nth-child("+start_index+"), li:nth-child("+start_index+1+"), li:nth-child("+start_index+2+")")
但我显然错过了n-child的观点,因为它挑选出的LI已经到处都是!
答案 0 :(得分:1)
The :nth-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings before it in the document tree
你可能做的是定义多个选择器:
li:nth-child(6n+1), li:nth-child(6n+2), li:nth-child(6n+3)
假设您要匹配元素1-3,7-9,13-15 ......(在三个组之间交替)
答案 1 :(得分:1)
试试此代码
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Style</title>
<style type="text/css">
button { display:block; font-size:12px; width:100px; }
div { float:left; margin:10px; font-size:10px;
border:1px solid black; }
span { color:blue; font-size:18px; }
#inner { color:red; }
td { width:50px; text-align:center; }
</style>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
</head>
<body>
<h2>Change color using jQuery for this list</h2>
<ul id="Mylist">
<li>1st</li>
<li>2nd</li>
<li>3rd</li>
<li>4th</li>
</ul>
<ul id="OtherOne">
<li>1st</li>
<li>2nd</li>
<li>3rd</li>
<li>4th</li>
</ul>
<script type="text/javascript">
var index=1
$('#Mylist li:nth-child('+index+')')
.css("background", "#ff0000")
.nextAll("li").slice(0, 2)
//.nextUntil('#Mylist li:nth-child('+(index+3)+')')
.css("background", "#ff0000");
</script>
</body>
</html>
答案 2 :(得分:0)
这对你有用吗?
var $lis = $("li:nth-child("+start_index+")"); // Just one li
$lis.add($nth.nextAll("li").slice(0, 2)); // Added its next two siblings
// Now $lis holds (up to) three lis
答案 3 :(得分:0)
var li = $("ul.list li");
for(var i = 0; i < li.length; i+=3) {
li.slice(i, i+3).wrapAll("<li><ul class='new'></ul></li>");
}
$(".new:odd").css("background-color", "#efc");
要反转结果,您可以使用:even
选择器代替:odd
。