如何使用 Javascript 或 jQuery 突出显示页面上出现的所有单词?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32130130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:53:45  来源:igfitidea点击:

How to highlight all occurrences of a word on a page with Javascript or jQuery?

javascriptjquerycsshighlighting

提问by T. Brian Jones

I have a list of keywords and then a list of sentences containing those keywords on a page. I'd like to make the keyword list clickable. When a user clicks on a keyword, all occurrences of that keyword would highlight in the sentences.

我有一个关键字列表,然后是一个包含页面上这些关键字的句子列表。我想让关键字列表可点击。当用户点击一个关键字时,该关键字的所有出现都会在句子中突出显示。

How can I do this with jQuery or raw Javascript?

如何使用 jQuery 或原始 Javascript 执行此操作?

The only way I can think is to wrap every word on the page with a class containing itself as the class name. Then make the keywords buttons that add a highlight class to the matching word classes. This may work, but seems like a LOT of unnecessary code injection.

我能想到的唯一方法是用一个包含自身作为类名的类来包装页面上的每个单词。然后制作关键字按钮,为匹配的词类添加突出显示类。这可能有效,但似乎有很多不必要的代码注入。

List of Keywords

关键字列表

<button>this</button>
<button>example</button>

Sentences

句子

<span class='word_this'>This</span> <span class='word_is'>is</span> <span class='word_an'>an</span> <span class='word_example'>example</span>.

回答by Rob M.

The best way is probably to use a .highlightclass to highlight the words and just wrap the matches in a span with that highlight class. Here is a basic example:

最好的方法可能是使用一个.highlight类来突出显示单词,然后将匹配项用该突出显示类包装在一个跨度中。这是一个基本示例:

var sentences = document.querySelector('#sentences');
var keywords = document.querySelector('#keywords');

keywords.addEventListener('click', function(event){
    var target = event.target;
    var text = sentences.textContent;
    var regex = new RegExp('('+target.textContent+')', 'ig');
    text = text.replace(regex, '<span class="highlight"></span>');
    sentences.innerHTML = text;
}, false);
.highlight {
    background-color: yellow;
}
<div id="keywords">
    <span>This</span> 
    <span>Example</span>.
</div>
<div id="sentences">
    This is an example. An example is shown in this. Here is another example.
</div>

Fiddle: https://jsfiddle.net/xukay3hf/3/

小提琴:https: //jsfiddle.net/xukay3hf/3/

Updated Fiddle which leaves existing word highlighting: https://jsfiddle.net/avpLn7bf/3/

更新的 Fiddle 保留现有单词突出显示:https: //jsfiddle.net/avpLn7bf/3/

回答by manji

You can wrap words with a specific class only when included in the search result. The wrapping will be removed the next time the word is not part of the search result:

仅当包含在搜索结果中时,您才可以使用特定类包装单词。下次该词不是搜索结果的一部分时,包装将被删除:

var highlightRe = /<span class="highlight">(.*?)<\/span>/g,
    highlightHtml = '<span class="highlight"></span>';

$(function() {
    $('#search').change(function() {
        var term = $(this).val();
        var txt = $('#txt').html().replace(highlightRe,'');
        if(term !== '') {
            txt = txt.replace(new RegExp('(' + term + ')', 'gi'), highlightHtml);
        }    
        $('#txt').html(txt);    
    });
});
.highlight {
    background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="text" id="search"/>

<div id="txt">
I have a list of keywords and then a list of sentences containing those keywords on a page. I'd like to make the keyword list clickable. When a user clicks on a keyword, all occurrences of that keyword would highlight in the sentences.

How can I do this with jQuery or raw Javascript?

The only way I can think is to wrap every word on the page with a class containing itself as the class name. Then make the keywords buttons that add a highlight class to the matching word classes. This may work, but seems like a LOT of unnecessary code injection.
</div>

回答by Mousey

The glossarizer plug-in will do this. You put your sentences into a JSON file and each occurrence is given a dotted underline and acts as a tooltip. Set the replaceOnceparameter to falsefor each occurrence to be highlighted. You can change the js file to customize the appearance, and add any heading tags containing the words, since normally people don't want those highlighted.

Glossarizer 插件将执行此操作。您将句子放入一个 JSON 文件中,每个出现的句子都有一个虚线下划线并作为工具提示。为每个要突出显示的事件设置replaceOnce参数false。您可以更改 js 文件以自定义外观,并添加任何包含单词的标题标签,因为通常人们不希望那些突出显示。