nth-child(),nth-of-type()中用变量作索引
<---------------html代码-------------->
<div>
<p>adgiejgjg</p>
<p>adgiejgjg</p>
<p>adgiejgjg</p>
<p>adgiejgjg</p>
</div>
<--------------js代码------------------>
通常这样用
$("p:nth-child(2)").css("color","rgba(255,204,0,1)");
能正常的改变第二个p的字体颜色
但若传入一个变量做为nth-child()的索引,如:
var index = 2;
将index代替上面代码$("p:nth-child(2)")中的2,
不知道要怎么写啊,求大神....
我下面的写法出现了错误:
var index = 2;
$('"p:nth-child(' + index + ')"').css("color","rgba(255,204,0,1)");
错误:
Error: Syntax error, unrecognized expression: "p:nth-child(2)"[color=#FF0000][/color]
------解决方案--------------------$('"p:nth-child(' + index + ')"').css("color","rgba(255,204,0,1)");
这样得出结果是
$('"p:nth-child(2)"').css("color","rgba(255,204,0,1)"); 所以错了
可以写成
$('p:nth-child(' + index + ')').css("color","rgba(255,204,0,1)");
或 $("p").eq(index-1).css("color","rgba(255,204,0,1)");