首页 > 解决方案 > 如何将css添加到与搜索框中的单词匹配的div中的单词?

问题描述

我有一个搜索框,您可以在其中搜索单词,页面将在页面描述中显示搜索到的单词(意思是如果您搜索的单词在页面描述中,那么它将显示指向页面的链接和页面描述)。我需要能够从结果中显示的描述中获取搜索的词,我需要在描述中突出显示该词。这是我到目前为止所拥有的。但这不起作用。

var searchValue = $(".search-query").val(); //searchValue is the word you type in the input box

$( ".searchResults-description:contains('" + searchValue + "')").css("background-color", "#fadcd9" ); 

请帮忙!当我点击搜索时,这个词会留在我的搜索框中。页面重新加载后,我将其重新放入输入框中。但我不需要在描述 div 中突出显示这个词,无论这个词出现在哪里。

标签: jqueryhtmlcss

解决方案


您正在检查页面加载时搜索框的值,因此该searchValue变量始终为空。您需要做的是在输入更改时获取值。一种方法是使用keyup 功能。这应该让你开始:

$(function() {

  $('.search-query').keyup(function() {
    var searchValue = $(".search-query").val();
    $( ".searchResults-description:contains('" + searchValue + "')").css("background-color", "#fadcd9" );
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="search-query" />

<div class="searchResults-description">Lorem</div>
<div class="searchResults-description">Ipsum</div>


推荐阅读