基于多个类之一的 switch case 语句

发布于 2024-10-17 18:05:28 字数 265 浏览 5 评论 0原文

我正在尝试实现这样的 switch case 语句:

switch (active.attr('class')){
    case "video": ...

        case "slideshow": ...
...

问题是,“视频”和“幻灯片”都是我尝试定位的 div 所具有的三个类之一,因此它与大小写不匹配。 ..

我基本上会怎么说“视频是 attr('class') 的一部分”?

谢谢, 卢茨

I'm trying to implement a switch case statement like this:

switch (active.attr('class')){
    case "video": ...

        case "slideshow": ...
...

The problem is, that "video" 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

你在看孤独的风景 2024-10-24 18:05:28

看起来您正在使用 jQuery,它提供了两种方法:

所以你可以调用:

if( active.hasClass('video') ) { }

if( active.is('.video') ) { }

注意 .is() 需要一个更具体的模式,以 .< /code> 但你也可以确定很多其他的东西,比如 .is('div') 等。

It looks like you're using jQuery, which offers two methods for that:

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.

叹沉浮 2024-10-24 18:05:28

您也许可以尝试拆分字符串。
我的脑海里浮现出:

var classes = active.attr('class').split(' ');
foreach(var c in classes) {
    switch(c) {
        case 'video'
        ...
        case 'slideshow'
        ...
    }
}

只是一个想法。上面的答案可能会以其他方式执行相同的操作:)

编辑:

您还可以像这样使用 jQuery .each()

classes.each(function(c) {
    switch(c) {
        case 'video'
        ...
        case 'slideshow'
        ...
    }
}

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'
        ...
    }
}
美人骨 2024-10-24 18:05:28

您可以使用 hasClass

查看此相关帖子。 我认为确实如此你想做什么。

You can use hasClass

See this related post. I think it does what you're looking to do.

小兔几 2024-10-24 18:05:28

使用 if 和 hasClass 方法:

if (active.hasClass('video')) {
}
else if {active.hasClass('slideshow')) {
}

如果您需要同时执行这两个操作(在开关上失败),删除 else 以便 if 语句是独立的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文