搜索功能是网站必须的一个模块,我们常常需要输入一个关键词,就想让所有跟这个关键词相关的结果都出来,并给关键词红色凸出显示,下面青岛星网跟大家分享下实现思路。
<form action="search.asp" method="post" name="form1"> <input name="key" type="text" class="bk" id="key" size="12" /> <input type="image" name="imageField" id="imageField" src="index/login.jpg" /> </form>
<% key=request("key") if key="" then response.write "<script>alert('查找字符串不能为空!');window.location='index.asp';</script>" response.end end if %>
这一步:单纯的判断不为空不能满足实际项目的需求,我们在这里可能要对搜索词进行更多的判断,例如:是否有违法字符等,如有违法字符则进行提示不进行后面的搜索,节省资源。扩展阅读:ASP违法字符检测函数
<% Set rs= Server.CreateObject("ADODB.Recordset") sql="select * from 表 where 字段名 Like '%"&replace(trim(key)," ","%' and 字段名 like '%")&"%' order by id desc" rs.open sql,conn,1,1 if rs.eof and rs.bof then response.write "<p align='center'>对不起,没有找到相关新闻</p>" else %>
<%=replace(rs("title"),key,"<font color=#FF0000><strong>" &key& "</strong></font>")%>
关键词标红显示主要用到了ASP的replace
函数,扩展阅读: ASP内置函数replace()的使用方法
更完美的关键词凸出高亮颜色显示实现方法扩展阅读: ASP搜索关键词自动加色高亮怎么实现