2012-12-14 26 views
0

我有一個包含2個或更多類名的jQuery對象(thisClass)。我想弄清楚如何只返回預定數組中的類名。在jQuery中的grep字符串

事情是這樣的:

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.] 
+1

你要找http://stackoverflow.com/questions/3196613/jquery-determine-if-ul-has-class-or-another-one什麼? – Colleen

+1

我認爲你正在尋找類方法。 http://api.jquery.com/hasClass/ – thatidiotguy

回答

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. 
}