将每个拆分结果与每个 class 元素进行比较

Compare each splitted result with each class element

var data = 'sky,sea,earth,moon';
var a = data.split(","), i;
for (i = 0; i < a.length; i++) {
    var b = a[i].text();
    $('mdcatsitem').each(function(){
        if (b == $(this).text()) {$(this).addClass('toggleright');}
    });
}

控制台:
Uncaught TypeError: a[i].text is not a function

我需要的:
- 将 data 分成几部分;
- 获取 each 部分的文本并将其与 each mdcatsitem;
的文本进行比较 - 如果匹配 - 添加 class 到 mdcatsitem

为什么要在字符串上调用 .text()

data 是一个定界字符串,在调用 .split() 之后 a 只是一个字符串数组:

['sky', 'sea', 'earth', 'moon']

当遍历a时,你可以直接引用a[i]作为你想要的字符串:

var b = a[i];
// b now equals the string, such as 'sky' or 'sea'

a[i].text() 替换为 a[i]

a[i] 不是 一个 dom 元素 而是一个 字符串 asplit 之后的数组 data.

a = ['sky', 'sea', 'earth', 'moon']

使用此代码:

var data = 'sky,sea,earth,moon';
var a = data.split(","), i;
for (i = 0; i < a.length; i++) {
    var b = a[i];
    $('mdcatsitem').each(function(){
        if (b == $(this).text()) {$(this).addClass('toggleright');}
    });
}