如何使用javascript或jquery实现网页关键字搜索功能

83qze16e  于 2022-12-29  发布在  jQuery
关注(0)|答案(1)|浏览(159)

我需要在输入区搜索关键字,页面上只显示匹配的关键字,而且文字会变红!我在网上搜索过,可以用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>
jobtbby3

jobtbby31#

请看下面的例子。

$(function() {
  $('#js-search').click(function() {
    $("p:contains(" + $('#keyWord').val() + ")").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>

如果你愿意,你可以使用inputValue变量,但是我看不出有什么好处。在click事件之前定义它也会导致它为空。在你的代码中,它会在页面加载时执行,而不是在按钮被单击时执行。你最终会在错误的时间捕获值。
对于contains,您需要将其与值串联。:contains Selector
对于$("p:contains(inputValue)"),选择器将查找文本inputValue,而$("p:contains(" + inputValue + ")")将连接到作为inputValue变量输入的任何内容。

相关问题