我需要在输入区搜索关键字,页面上只显示匹配的关键字,而且文字会变红!我在网上搜索过,可以用jquery完成,但是失败了~希望能得到你的帮助,谢谢
let inputValue = document.querySelector('#keyWord').value;
console.log(inputValue)
$('#js-search').on('click', function() {
$("p:contains(inputValue)").css('color', 'red');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="keyWord" type="text"><button id="js-search">search</button>
<ul>
<li>
<h1>Title</h1>
<p>Here is some text you can search to display keywords, but the text in the title does not need to be marked</p>
</li>ㄏ
<li>
<h1>Title</h1>
<p>Here is some text you can search to display keywords, but the text in the title does not need to be marked</p>
</li>
<li>
<h1>Title</h1>
<p>Here is some text you can search to display keywords, but the text in the title does not need to be marked</p>
</li>
<li>
<h1>Title</h1>
<p>Here is some text you can search to display keywords, but the text in the title does not need to be marked</p>
</li>
</ul>
1条答案
按热度按时间jobtbby31#
请看下面的例子。
如果你愿意,你可以使用
inputValue
变量,但是我看不出有什么好处。在click
事件之前定义它也会导致它为空。在你的代码中,它会在页面加载时执行,而不是在按钮被单击时执行。你最终会在错误的时间捕获值。对于
contains
,您需要将其与值串联。:contains Selector对于
$("p:contains(inputValue)")
,选择器将查找文本inputValue
,而$("p:contains(" + inputValue + ")")
将连接到作为inputValue
变量输入的任何内容。