木子屋 Dnawo's BLOG

加亮关键字

👤 dnawo 📅 2007-03-20 👁 5569 👍 0 💬 0 🔄 本站原创
一、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,但如果内容中碰巧包含有<的话,搜索结果就不是很准确,总得来说,这是众多方法中较好的了。

评论(0)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 ASP实现"相关新闻" 下一篇 → 什么是GPS/GIS/RS