最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery select elements by class using name from variable - Stack Overflow

programmeradmin0浏览0评论

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);

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');

basic basically I want affect all the elements with 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?

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);

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);

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');

basic basically I want affect all the elements with 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?

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);
Share Improve this question edited Sep 6, 2012 at 5:47 Ahsan Khurshid 9,4691 gold badge34 silver badges51 bronze badges asked Sep 6, 2012 at 5:37 ChatGPTChatGPT 5,61713 gold badges52 silver badges72 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 29

Selector is nothing more than just a string. So you could use

$('.' + classname)

where classname is a variable that holds particular class name

try changing your code like this

$('.' + x).show().addClass('active').siblings().hide().removeClass('active');
发布评论

评论列表(0)

  1. 暂无评论