本文实例讲述了基于正则表达式实现UL下LI的样式替换功能。分享给大家供大家参考,具体如下:
最先我想到是在UL下填充好在替换发觉结果差强人意,没有真正改变样式:
1
2
3
4
5
6
7
|
$( "#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前进行替换:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
$( "#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); } }); |
希望本文所述对大家正则表达式学习有所帮助。