我想用jquery选择几个元素:
$('p:nth-child(1),p:nth-child(4),p:nth-child(7),p:nth-child(10)')
//nth-child is : 1,4,7,10,13,16,19,22 and etc
我必须每3件商品选择1件商品。 如何用动态代码做到这一点?
答案 0 :(得分:1)
如果您想每3个选择一个项目,您可以执行以下操作:
$("p:nth-child(3n+1)")
例如,在这里我将设置“p”项目的背景颜色,但仅限于第1,第4,第7 ......:
$("p:nth-child(3n+1)").css("background-color", "red");
请参阅jsfiddle update:http://jsfiddle.net/TjLdy/1/
答案 1 :(得分:0)
您可以将要选择的子项存储在数组中,并使用循环生成选择器:
var children = [1,4,7,10,13,17,21,24],
selector = "";
// Loop through each value in your array, populating your selector string
// Each loop will add "p:nth-child(n)," to your selector string
for (var i=0; i<children.length; i++)
selector += "p:nth-child(" + children[i] + "),";
// Remove trailing comma
selector = selector.slice(0, -1);
这将生成以下selector
字符串:
"p:nth-child(1),p:nth-child(4),p:nth-child(7),p:nth-child(10),p:nth-child(13),p:nth-child(17),p:nth-child(21),p:nth-child(24)"
现在我们可以使用:
将它放入jQuery选择器中$(selector)