我正在尝试在 Jquery 中进行有效的实时搜索,但我没有成功捕捉到文本中的第一个词。我将每个单词都包裹在这样的范围内:
<span class="word word-this" id="word-#" aria-hidden="true">this</span>
对于脚本,我尝试在搜索的单词后面添加一个“已读”类。每次我转到下一个“this”时,所有“this”之前的单词都有“read”类。像那样:
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() 问题还是其他问题。
最佳答案
我发现了两个错误。
-
$('.word-'+word).first()
是第一个具有.word-<word>
的跨度. -
$(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');
});
};
关于Jquery 首先改变每个。不是 ('class' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50426485/