网络编程 
首页 > 网络编程 > 浏览文章

基于正则表达式实现UL下LI的样式替换功能

(编辑:jimmy 日期: 2024/10/10 浏览:3 次 )

本文实例讲述了基于正则表达式实现UL下LI的样式替换功能。分享给大家供大家参考,具体如下:

最先我想到是在UL下填充好在替换发觉结果差强人意,没有真正改变样式:

$("#UlContent li").each(function (index) {
  // alert(index + ': ' + $(this).text());
  var text = $(this).text();
  var regExp = new RegExp($("#search_content").val(), 'g');
  var newText = text.replace(regExp,"<span style=\"background-color:red;\">" + $("#search_content").val() + "</span>");//将找到的关键字替换,加上highlight属性;
  $(this).text(newText);//更新文章;
});

其实应该在填充进UL前进行替换:

$("#search_content").keyup(function () {
  if(CheckChinese($("#search_content").val()))
  {
   $.ajax({
    type: "POST",
    anync: true,
    url: "HelpCenterSuggestion.ashx",
    cache: false,
    dataType: "text",
    data: { m: $("#search_content").val() },
    success: function (result) {
     $("#UlContent li").remove();
      var regExp = new RegExp($("#search_content").val(), 'g');
      var newText = result.replace(regExp,"<span style=\"background-color:red;\">" + $("#search_content").val() + "</span>");//将找到的关键字替换,加上highlight属性;
      $("#UlContent").append(newText);
    }
   });

PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:

JavaScript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript

正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg

希望本文所述对大家正则表达式学习有所帮助。

上一篇:正则表达式环视概念与用法分析
下一篇:正则表达式(regular)知识(整理)
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。