如何使用Javascript或jQuery突出显示单词在页面上的所有出现? [英] How to highlight all occurrences of a word on a page with Javascript or jQuery?
问题描述
我在页面上有一个关键字列表,然后是包含这些关键字的句子列表.我想使关键字列表可点击.当用户点击某个关键字时,该关键字的所有出现都会在句子中突出显示.
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.
我该如何使用jQuery或原始Javascript?
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.
关键字列表
<button>this</button>
<button>example</button>
句子
<span class='word_this'>This</span> <span class='word_is'>is</span> <span class='word_an'>an</span> <span class='word_example'>example</span>.
推荐答案
最好的方法可能是使用.highlight
类突出显示单词,然后将匹配项与该突出显示类一起包裹在一个范围内.这是一个基本示例:
The best way is probably to use a .highlight
class to highlight the words and just wrap the matches in a span with that highlight class. Here is a basic example:
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">$1</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>
提琴: https://jsfiddle.net/xukay3hf/3/
更新的小提琴使现有单词突出显示: https://jsfiddle.net/avpLn7bf/3/
Updated Fiddle which leaves existing word highlighting: https://jsfiddle.net/avpLn7bf/3/
这篇关于如何使用Javascript或jQuery突出显示单词在页面上的所有出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!