陋室铭
永远也不要停下学习的脚步(大道至简至易)

posts - 2169,comments - 570,views - 413万

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

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;
            } 

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

posted on   宏宇  阅读(224)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2010-07-05 北京热死了
2009-07-05 北京下雨了,兴奋中
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示