I'm trying to implement a switch case statement like this:
switch (active.attr('class')){
case "video": ...
case "slideshow": ...
...
The problem is, that "v开发者_如何学运维ideo" and "slideshow" each are one of three classes the div I'm trying to target has, therefor it doesn't match the case...
How would I basically say "video is a part of attr('class')" ?
Thanks, Lutz
It looks like you're using jQuery
, which offers two methods for that:
.is()
help.hasClass()
help
So you can either call:
if( active.hasClass('video') ) { }
or
if( active.is('.video') ) { }
Notice that .is()
requires a more specific pattern with the leading .
but it you can determine lots of other things too like .is('div')
etc.
You could perhaps try and split the string. From the top of my head:
var classes = active.attr('class').split(' ');
foreach(var c in classes) {
switch(c) {
case 'video'
...
case 'slideshow'
...
}
}
Just an idea. The above answers might do the same in other ways :)
Edit:
You could also use jQuery .each()
like this:
classes.each(function(c) {
switch(c) {
case 'video'
...
case 'slideshow'
...
}
}
You can use hasClass
See this related post. I think it does what you're looking to do.
Use if and the hasClass method:
if (active.hasClass('video')) {
}
else if {active.hasClass('slideshow')) {
}
If you need to do both (fall-through on the switch), remove the else so the if statements are independent.
精彩评论