加亮关键字

一、JS法

1、单个关键字加亮
<div id="txt">
用JS让文章内容指定的关键字加亮
是这样的..
现在有这些关键字:美容,生活,购物
当在文章里头出现这些关键字,就把它加亮显示..
文章是生成静态页面的,而这些关键字是能随时更新的,所以我想用JS来实现...
</div>
<script language="JavaScript">
document.getElementById("txt").innerHTML = document.getElementById("txt")..innerHTML.replace(/文章/gi,"<font color=red>文章</font>");
</script>


2、多个关键字加亮
<div id="txt">
用JS让文章内容指定的关键字加亮
是这样的..现在有这些关键字:美容,生活,购物
当在文章里头出现这些关键字,就把它加亮显示..
文章是生成静态页面的,而这些关键字是能随时更新的,所以我想用JS来实现...
</div>
<script language="JavaScript">
document.getElementById("txt").innerHTML = document.getElementById("txt").innerHTML.replace(/(文章)|(关键字)|(功能)/gi,"<font color=red>$1$2$3</font>");
</script>


二、ASP法

1、用Replace实现
<%
Dim i, KeyWords, ArrKeyWords
Dim strLongWords
strLongWords = "日前,建设部表示尚未公布住房建设规划的城市,务必在12月20日前全面完成编制、公布和备案工作;尚未建立廉租住房制度的城市,必须在2006年年底前建立并实施。目前全国尚有65%的地级以上城市、91.1%的县级城市未公布住房建设规划的情况。"
If Request.QueryString("KeyWords")<>"" Then
   KeyWords = Request.QueryString("KeyWords")
   ArrKeyWords = Split(KeyWords, " ",-1,1)
  
   For i = LBound(ArrKeyWords) To UBound(ArrKeyWords)
       strLongWords = Replace(strLongWords, ArrKeyWords(i), "<font color='#FF0000'>" & ArrKeyWords(i) & "</font>")      
   Next      
End If
%>

此法没有考虑到内容中的HTML代码。

2、用Instr、Mid等函数实现(函数摘自PJBLOG)
'*************************************
'加亮关键字
'*************************************
Function highlight(byVal strContent,byRef arrayWords)
    Dim intCounter,strTemp,intPos,intTagLength,intKeyWordLength,bUpdate
    if len(arrayWords)<1 then highlight=strContent:exit function
    For intPos = 1 to Len(strContent)
        bUpdate = False
        If Mid(strContent, intPos, 1) = "<" Then
            On Error Resume Next
            intTagLength = (InStr(intPos, strContent, ">", 1) - intPos)
            if err then
              highlight=strContent
              err.clear
            end if
            strTemp = strTemp & Mid(strContent, intPos, intTagLength)
            intPos = intPos + intTagLength
        End If
            If arrayWords <> "" Then
                intKeyWordLength = Len(arrayWords)
                If LCase(Mid(strContent, intPos, intKeyWordLength)) = LCase(arrayWords) Then
                    strTemp = strTemp & "<span class=""high1"">" & Mid(strContent, intPos, intKeyWordLength) & "</span>"
                    intPos = intPos + intKeyWordLength - 1
                    bUpdate = True
                End If
            End If
        If bUpdate = False Then
            strTemp = strTemp & Mid(strContent, intPos, 1)
        End If
    Next
    highlight = strTemp
End Function

此法考虑到了内容中的HTML,但如果内容中碰巧包含有<的话,搜索结果就不是很准确,总得来说,这是众多方法中较好的了。

上一篇: ASP实现"相关新闻"
下一篇: 什么是GPS/GIS/RS
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags:
最新日志:
评论: 1 | 引用: 0 | 查看次数: 5075
发表评论
登录后再发表评论!