jQuery使用变量名称通过类选择元素 [英] jquery select elements by class using name from variable
问题描述
我想在jQuery中对与某个类名匹配的所有元素进行处理.类名来自变量.如何使用变量通过类进行选择?
I want to do somethings in jQuery to all the elements which match on a certain class name. The class name comes from a variable. How do I do the select using by class using my variable?
var x = $(this).attr('href').slice(1);
这会将x
设置为等于我想要的class
的名称.
this will set x
equal to the name of the class
I want.
现在我要选择具有该类名称的所有元素
now I want to select all the elements with that class name
我尝试类似的方法,但是它不起作用
I try stuff like this but it doesn't work
$(.x.show().addClass('active').siblings().hide().removeClass('active');
基本上,我想在class = x
最后,不是将x
设置为类名,而是可以在第一个变量赋值中获取类的array
吗?
Finally, instead of setting x
to the class name, can I just get my array
of classes in the first variable assignment?
即代替
var x = $(this).attr('href').slice(1);
我可以这样做吗?[pseudo code]:
can I do this [pseudo code]:
var x = classname is $(this).attr('href').slice(1);
推荐答案
选择器不过是一个字符串而已.所以你可以使用
Selector is nothing more than just a string. So you could use
$('.' + classname)
其中classname
是保存特定类名的变量
where classname
is a variable that holds particular class name
这篇关于jQuery使用变量名称通过类选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!