简体   繁体   English

多个类上的jQuery选择器

[英]jQuery selector on multiple classes

This finds the id but does not remove the class 这会找到ID,但不会删除该类

$('[id^=paritalIDname]').removeClass('[class^=partialClassName]');

Probably because the element looks like 可能是因为该元素看起来像

<div id="partialIDname-full" class="something someone partialClassNameFull">

Whether the element has a class name of partialClassNameFull or partialClassNameHalf I need to remove it. 无论元素的类名称为partialClassNameFull还是partialClassNameHalf我都需要将其删除。

I thought I could use a wildcard in the class selector, like 我以为可以在类选择器中使用通配符,例如

removeClass('[class^=partialClassName*]');

but that's not working. 但这不起作用。

What is a good solution? 有什么好的解决方案? (Thanks.) (谢谢。)

This will handle all partial match. 这将处理所有部分匹配。

        $("div[id^=partialId]").each(function () {
            var cls = $(this).attr("class").split(" ");

            for (var i in cls) {
                if (/partialClass/.test(cls[i])) {
                    $(this).removeClass(cls[i]);
                    break;
                }
            }
        });

You need to explicitly remove both classes: 您需要显式删除这两个类:

$('[id^=partialIDname]').removeClass('partialClassNameFull').removeClass('partialClassNameHalf');

Because .removeClass() only works on full class name matches. 因为.removeClass()仅适用于完整的类名匹配。 If one of the class names is not present, then nothing will happen - no error is thrown when you try to .removeClass() a class that is not present. 如果一个类名不存在,那么将不会发生任何事情-当您尝试.removeClass()一个不存在的类时,不会引发任何错误。

You can also try out as suggested in the comments the briefer version of: 您也可以按照注释的建议尝试使用以下简短版本:

$('[id^=partialIDname]').removeClass('partialClassNameFull partialClassNameHalf');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM