繁体   English   中英

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

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

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

我怎么能用jQuery或原始Javascript做到这一点?

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

关键字列表

<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类来突出显示单词,然后将匹配包装在该高亮类的跨度中。 这是一个基本的例子:

 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/

只有包含在搜索结果中时,才能使用特定类包装单词。 下次单词不是搜索结果的一部分时,将删除包装:

 var highlightRe = /<span class="highlight">(.*?)<\\/span>/g, highlightHtml = '<span class="highlight">$1</span>'; $(function() { $('#search').change(function() { var term = $(this).val(); var txt = $('#txt').html().replace(highlightRe,'$1'); 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> 

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM