首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

nth-child(),nth-of-type()顶用变量作索引

2013-09-29 
nth-child(),nth-of-type()中用变量作索引---------------html代码--------------divpadgiejgjg/p

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] javascript nth-child() nth-of-type() jquery
[解决办法]
$('"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)"); 

热点排行