jquery - 如何将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 中突出显示这个词,无论这个词出现在哪里。
解决方案
您正在检查页面加载时搜索框的值,因此该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>
推荐阅读
- javascript - 使用 smtpjs 在纯 javascript 中发送表单的值
- google-bigquery - 如何使用 Google 工具和 JavaScript 存储和提供优惠券
- c++ - 任何人都可以在 switch 语句上方解释这个函数定义吗?
- java - Netbeans java jar 与 javadocs 和源使用 xml 和属性文件
- java - 如何通过端口转发在 Internet 上使用 SSL 部署 MQTT?
- python - 排名线图定制
- python - 如何在 Python 中计算类变量?
- java - 无法使用外部类按降序对数组进行排序
- python - 破折号返回't.split 不是函数'错误'
- javascript - 使用for await...of时如何获取key值