Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/463.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery中的Grep字符串_Javascript_Jquery - Fatal编程技术网

Javascript jQuery中的Grep字符串

Javascript jQuery中的Grep字符串,javascript,jquery,Javascript,Jquery,我有一个包含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.

我有一个包含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.]

嗯,首先,
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.
}
var thisClass=$(this.attr(“类”);
var结果=[];
如果(本类){
thisClass=thisClass.split(“”);
对于(var i=0;i
您在寻找什么?我想您在寻找类方法。