Asp.net 中高亮显示搜索关键字简单方法

今天用到搜索时的高亮显示,百度了一下,如下面:

1.替换关键字,对字体变色。
复制代码
        public static string ReplaceRed(string strtitle, string  redkey)
        
{
            if (redkey == "" || redkey == null
)
            
{
                return
 strtitle;
            }
            else
                strtitle = strtitle.Replace(redkey, " <font color='#ff0000'>" + redkey + " </font>");
            return
 strtitle;
        }
复制代码

2.用正则,CSS背景变色。
复制代码
        protected string HighlightText(string inputText,string  searchWord)
        
{
            System.Text.RegularExpressions.Regex expression = new System.Text.RegularExpressions.Regex(searchWord.Replace(" ""|"
), System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            return expression.Replace(inputText,new
 System.Text.RegularExpressions.MatchEvaluator(ReplaceKeywords));
        }
        public string ReplaceKeywords(System.Text.RegularExpressions.Match m)
        
{
            return "<span class='highlightTxtSearch'>" + m.Value + "</span>"
;
        }
复制代码

CSS:
.highlightTxtSearch
{
    background-color:Yellow;
}

 

上面的方法固然用着不错,但感觉过于繁琐。于是试着用下面的方法:

     //声明关键字数组
            string[] m_Key = new string[] { };

      //搜索关键字不空,就执行替换
            if (!string.IsNullOrEmpty(Request.QueryString["SearchKey"]))//或者 if (!string.IsNullOrEmpty(txtSearchKey.Text.Trim()))
            {

               //搜索关键字以空格隔开
                m_Key = Request.QueryString["SearchKey"].Split(new char[] { ' ' });
                for (int i = 0; i < m_Key.Length; i++)
                {
                    lblOptimumRoad.Text = modelRoadSearch.OptimumRoad.Replace(m_Key[i], "<span class='highlightTxtSearch'>" + m_Key[i] + "</span>");

               //如果在gridview中,可以在RowDataBound事件中进行判断,然后e.Row.Cells[3].Text = e.Row.Cells[3].Text.Replace(m_SearchKey[i], "<span class='highlightTxtSearch'>"+m_SearchKey[i]+"</span>");
                }
            }
            else
            {
                //搜索关键字为空,则是从其它页面转来,不用高亮关键字
                lblOptimumRoad.Text = modelRoadSearch.OptimumRoad;
            } 

不管这种方法效率如何,但感觉用着挺方便的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值