【问题标题】:Jquery change each first .not('class')Jquery 更改每个第一个 .not('class')
【发布时间】:2018-10-29 18:58:01
【问题描述】:

我正在尝试在 Jquery 中进行有效的实时搜索,但我没有成功捕捉到文本中的第一个单词。我将每个单词都包装在这样的范围内:

<span class="word word-this" id="word-#" aria-hidden="true">this</span>

对于脚本,我尝试在我搜索的单词后面添加一个“已读”类。每次我去下一个“this”,之前的所有“this”单词都会被全班“阅读”。像这样:

var word = function(word) {
  $('span').each(function() {
    if ($(this).not('.readed') && $(this).hasClass('word-'+word)){
      // transformation
      $('.word-'+word).first().css('color', 'red').addClass('readed');
    }
  });
};

问题是它捕获了单词的第一次出现但没有找到下一个,它停留在第一个。它不承认添加了“已读”类。我不知道是 .first() 还是 .not() 问题还是其他问题。

【问题讨论】:

    标签: jquery css jquery-selectors unrecognized-selector livesearch


    【解决方案1】:

    我发现了两个错误。

    • $('.word-'+word).first() 是第一个具有 .word-&lt;word&gt; 的跨度。
    • $(this).not('.readed') 是一个对象,因此作为 if 语句的条件,它始终为真。

    这是工作代码:

    var word = function(word) {
      $('span').not('.readed').each(function() {
        if ($(this).hasClass('word-'+word)) {
          // transformation
          $(this).css('color', 'red').addClass('readed');
          // interrupt the each loop
          return false;
        }
      });
    };
    

    我找到了一个更简单的实现。

    var word = function(word) {
      $('span.word-'+word).not('.readed').first().each(function() {
        $(this).css('color', 'red').addClass('readed');
      });
    };
    

    【讨论】:

    • 当我这样做时,每个有 .word-&lt;word&gt; 的跨度都会改变
    • 请让我撤回答案。对不起。
    • 它运行!谢谢@set0gut1
    • @FlorianFromager 我找到了一个更简单的实现并在我的帖子中添加了它:)
    猜你喜欢
    • 1970-01-01
    • 2012-09-03
    • 1970-01-01
    • 2010-10-31
    • 2013-06-28
    • 2013-08-21
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    相关资源
    最近更新 更多