最先我想到是在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); } });原文链接:https://www.f2er.com/regex/359928.html