【发布时间】:2023-01-04 22:58:24
【问题描述】:
我用javascript做一个搜索关键词,针对特定的关键词会显示高亮文字的功能,但是现在有问题了!希望在搜索下一个关键词的时候,之前的高亮文字可以恢复到原来的黑色,而不是在搜索下一个关键词的时候,之前搜索的关键词被标记为红色,请问这段代码怎么办?可以做些什么来优化这个问题?谢谢大家的答案。
let search = document.querySelector('#js-search');
let content = document.querySelector('p');
let key = document.querySelector('#keyWord').value;
function highlight(content, key){
return content.replace(new RegExp(key,'gi'),(match)=>{
return `<span style="color:red">${match}</span>`;
});
}
search.addEventListener('click',() =>{
const keyword = $('#keyWord').val();
const matchs = $("p:contains("+ keyword +")");
matchs.each(function(){
const content = $(this).html();
$(this).html(highlight(content,keyword));
});
});
.red{
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>eturn problem</h1>
<p>I am an example of related content</p>
</li>
<li>
<h1>credit card problem</h1>
<p>This is about credit card issues, you can search for keywords to find keywords</p>
</li>
<li>
<h1>order cancellation problem</h1>
<p>order cancellation problemThis is a sample text of random typing content</p>
</li>
</ul>
【问题讨论】:
标签: javascript html jquery css