Javascript jquery使用变量中的名称按类选择元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12293587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery select elements by class using name from variable
提问by Max Hodges
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?
我想在 jQuery 中对匹配某个类名的所有元素做一些事情。类名来自一个变量。如何使用我的变量按类进行选择?
var x = $(this).attr('href').slice(1);
this will set x
equal to the name of the class
I want.
这将设置为x
等于class
我想要的名称。
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');
basic basically I want affect all the elements with where class = x
基本基本上我想用 where 影响所有元素 class = x
Finally, instead of setting x
to the class name, can I just get my array
of classes in the first variable assignment?
最后,不是设置x
为类名,我可以array
在第一个变量赋值中获取我的类吗?
i.e. instead of
即代替
var x = $(this).attr('href').slice(1);
can I do this [pseudo code]:
我可以这样做吗[伪代码]:
var x = classname is $(this).attr('href').slice(1);
回答by zerkms
Selector is nothing more than just a string. So you could use
选择器只不过是一个字符串。所以你可以使用
$('.' + classname)
where classname
is a variable that holds particular class name
whereclassname
是一个保存特定类名的变量
回答by rahul
try changing your code like this
尝试像这样改变你的代码
$('.' + x).show().addClass('active').siblings().hide().removeClass('active');