从文本输入中突出显示div中所有匹配的单词 [英] highlighting all matching words in div from text input

查看:95
本文介绍了从文本输入中突出显示div中所有匹配的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个突出显示div中匹配词的功能。但是如果有两个相同的单词用不同的单词分隔,那么只有第一个单词是高亮的。例如,如果搜索标准是烧伤一词,而文中则是烧伤宝宝烧伤一句,我想让它突出显示烧伤。这 jsFiddle 演示了它如何突出显示第一个刻录。下面的代码也是。任何帮助非常感谢。感谢您的阅读。

css

  .highlight {
font-weight:bold;
颜色:绿色;

html

 < input id =searchtype =textvalue =burn> 
< div class =searchable>刻录宝宝刻录< / div>

javascript

  if($('#search').val().length!== 0){
$('。searchable')。each(function(){
$(this ).html($(this).html()。replace($('#search').val(),< span class ='highlight'>+ $('#search')。val )+< / span>));
});


解决方案

换成replace()而不是字符串,用g修饰符替换执行全局匹配。

  if($(' #search')。val().length!== 0){
$('。searchable')。each(function(){
var search_value = $(#search).val ();
var search_regexp = new RegExp(search_value,g);
$(this).html($(this).html()。replace(search_regexp,< span class = 'highlight'>+ search_value +< / span>));
});
}


I have made a function which highlights matching words in a div. but if there are two identical words separated by a different word then only the first word is highlight. so for example if the search criterion was the word "burn", and in the text was the sentence "burn baby burn", I would want it to highlight both "burn"'s. this jsFiddle demonstrates how it only highlights the first "burn". Here is the code below also. Any help much appreciated. Thanks for reading.

css

.highlight{
            font-weight:bold;
            color:green;
}

html

<input id = "search" type ="text" value = "burn">
<div class = "searchable">burn baby burn</div>

javascript

if($('#search').val().length !== 0){
   $('.searchable').each(function(){
   $(this).html($(this).html().replace($('#search').val(),"<span class = 'highlight'>"+$('#search').val()+"</span>"));
 });
}

解决方案

You can pass a regular expression into replace() instead of the string, with the g modifier to make replace perform a global match.

if($('#search').val().length !== 0){
   $('.searchable').each(function(){
   var search_value = $("#search").val();
   var search_regexp = new RegExp(search_value, "g");
   $(this).html($(this).html().replace(search_regexp,"<span class = 'highlight'>"+search_value+"</span>"));
 });
}

这篇关于从文本输入中突出显示div中所有匹配的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆