日期:2014-5-16 浏览次数:20318次 点赞次数:20

急!JS显示关键字高亮问题
用JS显示关键字高亮静态页面现已实现,可是现在是把我后台的数据取到后显示高亮,数据是循环显示的,只取到了第一行数据,不知道如何做了,请高手看下

------解决方案--------------------
那就用正则吧 如果是<>尖括号里面的就不替换
为了防止原来标签输入不规范 做了曲折处理
JScript code

       var html = "<div>div and other content</div>";
       var word = "div";
       var replaceContent = "111";
       var reg1 = new RegExp("([\\<][^\\<\\>]*)(" + word + ")([^\\>\\<]*[\\>])", "ig");
       var str1 = html.replace(reg1, "$1{" + "$2" + "}$3");
       alert(str1);
       var reg2 = new RegExp("(^|[^\\{]+)" + word + "([^\\{]+|$)", "ig");
       var str2 = str1.replace(reg2, "$1" + replaceContent + "$2");
       alert(str2);
       var reg3 = new RegExp("\\{" + word + "\\}", "ig");
       var str3 = str2.replace(reg3, word);
       alert(str3);

------解决方案--------------------
替换了之后你要把值赋回去啊 要不怎么替换呢

[code=JScript]
//关键字高亮
function highLight(keyWords)
{
if(keyWords !=null)
{
var array = keyWords.substring(1,keyWords.length-1);
array = array.split( ", ");
var html = document.getElementById( "tds ").innerHTML;
for(var i=0;i <array.length;i++)
{
var oneKey = array[i];
var replaceContent = " <a style= 'color:red '> "+oneKey+ " </a> ";
var reg1 = new RegExp( "([\\ <][^\\ <\\> ]*)( " + oneKey + ")([^\\> \\ <]*[\\> ]) ", "ig ");
var str1 = html.replace(reg1, "$1{ " + "$2 " + "}$3 ");
var reg2 = new RegExp( "(^|[^\\{]+) " + oneKey + "([^\\{]+|$) ", "ig ");
var str2 = str1.replace(reg2, "$1 " + replaceContent + "$2 ");
var reg3 = new RegExp( "\\{ " + oneKey + "\\} ", "ig ");
html = str2.replace(reg3, oneKey);

}
document.getElementById( "tds ").innerHTML = html;
}

}

[/code]