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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:38:23  来源:igfitidea点击:

jquery select elements by class using name from variable

javascriptjqueryjquery-selectors

提问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 xequal to the name of the classI 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 xto the class name, can I just get my arrayof 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 classnameis a variable that holds particular class name

whereclassname是一个保存特定类名的变量

回答by rahul

try changing your code like this

尝试像这样改变你的代码

$('.' + x).show().addClass('active').siblings().hide().removeClass('active');