0

我有一个包含 2 个或更多类名的 jQuery 对象 (thisClass)。我试图弄清楚如何只返回预定数组中的类名。

像这样的东西:

var thisClass = $(this).attr("class");
var icons = ["glass","leaf","dog","home"];

[Use grep here to return thisClass only as a single class name that is filtered by, or contained in icons.]
4

1 回答 1

1

嗯,首先,attr方法返回字符串而不是 jQuery 对象。在这种情况下,它返回所有 CSS 类用空格分隔的字符串。如果没有类,则返回undefined. 所以,你可能想试试这个代码:

var thisClass = $(this).attr("class");
var result = [];

if(thisClass) {
    thisClass = thisClass.split(' ');
    for(var i = 0; i < thisClass.length; i++) {
        if(icons.indexOf(thisClass[i]) !== -1) {
            result.push(thisClass[i]);
        }
    }
} else {
    // return; or something. There is no classes.
}
于 2012-12-14T19:42:17.947 回答