本文實例講述了基于正則表達式實現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); } });
希望本文所述對大家正則表達式學習有所幫助。
新聞熱點
疑難解答