1,
function keyQuery() { //移除之前的高亮文本 $("#FirstGuide p span").each(function () { var s = $(this).html(); $(this).replaceWith(s); }); //取得所有对象,并对默认自定义的方法进行遍历操作 $('#FirstGuide p').each(function () { //取得标签的文本 var t = $(this).text(); //取得需要查出的关键字,我们这里假定是多关键字以","间隔 var array = $.trim($('[data-query-text]').val()).split(","); //开始用关键字遍历标签文本 for (var i = 0; i < array.length; i++) { //判断标签是否包含关键字 if (t.indexOf(array[i]) > -1) { //定义正则表达式对象 array[i]是关键字 "g"是指全局范围 var a = new RegExp(array[i], "g") //对标签文本进行全局替换,包含关键字的位置替换为加红字span对象 t = t.replace(a, ("<span style='color:#F00'>" + array[i] + "</span>")); //将替换完的文本对象赋给此对象中A标签对象的html值中 //$(this).find("a").html(t); $(this).html(t); } } }); };
2,