第一步,页面部分
//项目版本
@{
var t=1;
}
<div>
@foreach(var item in Modle.xxx){//Model为服务器端返回来的总条数数据
<div class="selfClass"id="selelet@(t)">@item.Content</div>
t++;
} </div>
//原理解析版本
<div> <div class="selfClass"id="sel1">dfsdfkkksdfdsfsdfdsf你好dsfsfsfsf</div> <div class="selfClass"id="self2">dfsdfkkksdfdsfsdfdsf你好dsfsfsfsf</div> <div class="selfClass"id="self3">dfsdfkkksdfdsfsdfdsf你好dsfsfsfsf</div> </div>
<div id="shoWId" style=" 100px;height:200px;background-color: #018eea">
<button>点击</button></div> //按钮
3.jquery
$("#shoWId>button").click(function () { var Content=new Array();//存放文本内容的容器 var guanzi="kkk";//关键字不能为空,所以在项目中需要在此处获取搜索框里面的关键词,并判断不为空是才去执行以下部分 var SelfContent=document.getElementsByClassName("selfClass"); for(var i=0;i<SelfContent.length;i++){ Content.push(SelfContent[i].innerText); } for(var k=0;k<Content.length;k++){ togod(Content[k],guanzi,k); } }); function togod(contentStr,key,KID) { var set=""; var positionKey=contentStr.indexOf(key); var positionArray=new Array();//存放关键字在文本中的文字的容器 while (positionKey>-1){ positionArray.push(positionKey); positionKey=contentStr.indexOf(key,positionKey+1); } for(var j=0;j<positionArray.length;j++){ var s1=contentStr.substring(0,positionArray[j]); var s2='<span style="color: red;">'+key+'</span>'; var s3=contentStr.substring(positionArray[j]+key.length,contentStr.length); set=s1+s2+s3;//重新组装 }
var currentId = "select" + KID; document.getElementById("currentId").innerHTML=set;//重新渲染 }
以下是一个例子:
第一,Html部分:
@{ y=0;
var omit="..."; } <div class="dxcsearch_content_result_list_title" id="cateMessage@(y)"> @if (item.Title.Length > 45) { @item.Title.Substring(0, 45)@omit } else { @item.Title } </div>
第二,Jquery部分
<script> var content = new Array() var cateMessage = "@Model.CateMessage";//关键字是从服务器端返回的 var contentList = document.getElementsByClassName('dxcsearch_content_result_list_title'); if (cateMessage!="") { for (var i = 0; i < contentList.length; i++) { content.push(contentList[i].innerText); } for (var k = 0; k < content.length; k++) { searchSubStr(content[k], cateMessage, k); } function searchSubStr(str, subStr, p) { var set = ""; var pos = str.indexOf(subStr); var positions = new Array(); while (pos > -1) { positions.push(pos); pos = str.indexOf(subStr, pos + 1); } for (var j = 0; j < positions.length; j++) { var s1 = str.substring(0, positions[j]); var s2 = '<span style="color:#fe8081">' + cateMessage + '</span >'; var s3 = str.substring(positions[j] + cateMessage.length, str.length); set = s1 + s2 + s3; } var currentId = "cateMessage" + p; document.getElementById(currentId).innerHTML = set; } } </script>