本文實(shí)例講述了基于正則表達(dá)式實(shí)現(xiàn)UL下LI的樣式替換功能。分享給大家供大家參考,具體如下:
最先我想到是在UL下填充好在替換發(fā)覺(jué)結(jié)果差強(qiáng)人意,沒(méi)有真正改變樣式:
$("#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>");//將找到的關(guān)鍵字替換,加上highlight屬性; $(this).text(newText);//更新文章;});
其實(shí)應(yīng)該在填充進(jìn)UL前進(jìn)行替換:
$("#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>");//將找到的關(guān)鍵字替換,加上highlight屬性; $("#UlContent").append(newText); } });
PS:這里再為大家提供2款非常方便的正則表達(dá)式工具供大家參考使用:
JavaScript正則表達(dá)式在線測(cè)試工具:
http://tools.VeVB.COm/regex/javascript
正則表達(dá)式在線生成工具:
http://tools.VeVB.COm/regex/create_reg
希望本文所述對(duì)大家正則表達(dá)式學(xué)習(xí)有所幫助。
新聞熱點(diǎn)
疑難解答