2010-12-21 43 views
0

你好,我有以下代碼,它工作正常,查找和替換字符串...但它不是全球工作..如何使其作爲全球工作和更換後我想要將該字符串突出顯示爲綠色..如何..?如何應用背景顏色找到的文本

<!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> 

回答

1
$('body').html($('body').html().replace(oldstr, '<span style="color: green">' + newstr + '</span>')); 
+0

確定它是好的改變顏色..但在全球範圍內找到一個字符串替換所有在一個時間什麼做... – Mihir 2010-12-21 04:26:21

+0

@Mihir:就是這樣 - 在頁面主體中替換每一個出現的'oldstr'。這不是你「全球」的意思嗎?但是要小心,這基本上重新創建了整個頁面 - 所有的事件處理程序和jquery數據都會被吹走。 – sje397 2010-12-21 04:28:04

+0

@ sje397,這是不是昂貴的代碼行?我不是說它的壞或somthing,只是問這樣的 – kobe 2010-12-21 04:29:59

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>')); 
}