Javascript 在CSS选择器中使用变量

Javascript 在CSS选择器中使用变量,javascript,css-selectors,Javascript,Css Selectors,这可能是一个非常愚蠢的问题,但我有一个CSS选择器: $('.result:nth-child(25) .name .title') 这很有效。但是当我设置一个变量a=25时,它就中断了 $('.result:nth-child(a) .name .title') Uncaught Error: Syntax error, unrecognized expression: :nth-child 我做错了什么?您必须在JavaScript中使用字符串连接手动将值插入字符串中。请尝试以下方法

这可能是一个非常愚蠢的问题,但我有一个CSS选择器:

$('.result:nth-child(25) .name .title')
这很有效。但是当我设置一个变量a=25时,它就中断了

$('.result:nth-child(a) .name .title')

 Uncaught Error: Syntax error, unrecognized expression: :nth-child

我做错了什么?

您必须在JavaScript中使用字符串连接手动将值插入字符串中。请尝试以下方法:

$('.result:nth-child(' + a + ') .name .title')

也许你想要的是
$('.result:nth child('+a+').name.title')
不要粗鲁,但你可以用谷歌搜索你的问题标题来获得答案