你好我有以下代码,它适用于查找和替换字符串...但它不是全局工作..如何使其工作全局和更换后我想突出该字符串为绿色..如何..?
<!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>
答案 0 :(得分:1)
$('body').html($('body').html().replace(oldstr, '<span style="color: green">' + newstr + '</span>'));
答案 1 :(得分:0)
我认为这是你需要做的事情:
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>'));
}