今天用到搜索时的高亮显示,百度了一下,如下面:
{
if (redkey == "" || redkey == null)
{
return strtitle;
}
else
strtitle = strtitle.Replace(redkey, " <font color='#ff0000'>" + redkey + " </font>");
return strtitle;
}
2.用正则,CSS背景变色。
{
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:
{
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;
}
不管这种方法效率如何,但感觉用着挺方便的。