首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将背景颜色应用于找到的文本

如何将背景颜色应用于找到的文本
EN

Stack Overflow用户
提问于 2010-12-21 12:11:51
回答 2查看 99关注 0票数 0

你好,我有以下代码,它可以很好地查找和替换字符串…但是它不能使globally..how全局工作,并且在替换后,我想将该字符串突出显示为绿色。怎么..?

代码语言:javascript
运行
复制
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
 <script type="text/javascript" src="../js/jquery-1.4.2.min.js"></script>
 <script>
$(document).ready(function(){
$('#replace').click(function(){
var oldstr=$('#inputstring').val();
var newstr=$('#newstring').val();
var para=$('#para').html();
var result=$('p:contains('+oldstr+')');


if(result)
{
var x=para.replace(new RegExp(oldstr, 'i','g'), newstr);
$('#para').empty().html(x);

}
})
})
 </script>
 </head>

 <body>
  Enter the string to find:<input type="text" id="inputstring"><br>
  Enter string to replace:<input type="text" id="newstring"><br>
  <input type="button" value="Replace" id="replace"><br>
  <p id="para">This is the new paragraph written to test how to replace the a string  with desired string</p>
 </body>
</html>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-12-21 12:20:27

代码语言:javascript
运行
复制
$('body').html($('body').html().replace(oldstr, '<span style="color: green">' + newstr + '</span>'));
票数 1
EN

Stack Overflow用户

发布于 2013-01-04 02:54:49

我认为这就是你需要做的:

代码语言:javascript
运行
复制
if(result){
     var x=para.replace(new RegExp(oldstr, 'i','g'), newstr);
     $('#para').empty().html(x);
     $('#para').html($('#para').html().replace(oldstr, '<mark>' + newstr + '</mark>'));
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4496216

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档