美文网首页
实现搜索时把对应的搜索到的字变颜色

实现搜索时把对应的搜索到的字变颜色

作者: php转go | 来源:发表于2023-08-03 14:33 被阅读0次

用于在HTML中的<p>元素中搜索关键字,并将匹配的关键字用<mark>标签包围,以便突出显示。

使用Jquery来实现

<p class="msg">是我</p>
<p class="msg">我来啦</p>
<p class="msg">我在这里</p>
<p class="msg">你在干嘛</p>
<script>
    const searchTerm = '我';
    $('.msg').each(function() {
        if ($(this).text().includes(searchTerm)){
            $(this).html($(this).text().replace(new RegExp(`${searchTerm}`, 'g'), function (match) {
                return '<mark>' + match + '</mark>';
            }))
       }
    });
</script>

首先使用$('.msg')来选择所有具有class="msg"的<p>元素。然后,使用each()函数来遍历这些元素,并在每个元素上执行一个回调函数。
在回调函数中,使用$(this).text()来获取当前元素的文本内容,并使用includes()函数来检查该文本是否包含搜索字符串。如果包含,则使用$(this).html()来更新当前元素的HTML内容,以便在匹配的文本中使用<mark>标签包围搜索字符串。

使用原生JavaScript来实现

<p class="msg">是我</p>
<p class="msg">我来啦</p>
<p class="msg">我在这里</p>
<p class="msg">你在干嘛</p>
<script>
    const searchTerm = '我';
    const terms = document.querySelectorAll('.msg');
    terms.forEach(term => {
        if (term.textContent.includes(searchTerm)) {
            term.innerHTML=term.firstChild.nodeValue.replace(new RegExp(`${searchTerm}`, 'g'), function (match) {
                return '<mark>' + match + '</mark>';
            })
        }
    });
</script>

原理跟jq一样

相关文章

网友评论

      本文标题:实现搜索时把对应的搜索到的字变颜色

      本文链接:https://www.haomeiwen.com/subject/kwbnyltx.html