【问题标题】:Compare each splitted result with each class element将每个拆分结果与每个类元素进行比较
【发布时间】:2017-06-14 03:08:12
【问题描述】:
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部分的文本并将其与eachmdcatsitem的文本进行比较;
- 如果匹配 - 添加一个类到mdcatsitem

【问题讨论】:

  • $('mdcatsitem').filter(function(i, el) { return a.includes(el.textContent) }).addClass('toggleright')

标签: javascript jquery arrays string jquery-selectors


【解决方案1】:

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');}
    });
}

【讨论】:

    【解决方案2】:

    你为什么在字符串上调用.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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-03
      • 1970-01-01
      • 1970-01-01
      • 2013-06-06
      • 2017-10-30
      • 1970-01-01
      相关资源
      最近更新 更多