搜索结果关键字高亮显示

String.prototype.highlight = function(word) {

if(!word) throw new Error('WordRequired');

 

return this.replace(new RegExp(word,'gi'), function(w){

return '<strong class="text-danger">'+w+'</strong>';

});

};

 

$(function() {

$('#eventSearchId').click(function (e) {

e.preventDefault();

 

var keyword = $('#keywordId').val();

var sportName = $('#sportId').val();

var eventTypeId = $('#eventTypeId').val();

if(!keyword){

alert("please input league/team/eventId keyword");

return;

}

 

if(keyword.length < 2){

alert("please keyword's length must be greater than 2");

return;

}

 

$.ajax({

url : 'searchEvents',

data : {

keyword : keyword,

sportName:sportName,

eventTypeId:eventTypeId

},

dataType : 'json',

type : 'POST',

success : function(res) {

var searchContentDiv = $("#searchContentId");

searchContentDiv.empty();

searchContentDiv.append("<table border='8' id='searchContentTableId' align='center'></table>");

$("#searchContentTableId").append("<tr><td>EventId</td><td>Date</td><td>LeagueName</td><td>HomeTeam</td><td>AwayTeam</td><td>Operation</td></tr>");

for(var i = 0;i<res.length;i++) {

$("#searchContentTableId").append("<tr>" +

"<td>"+res[i].eventId.highlight(keyword)+"</td>" +

"<td>"+res[i].dateTime+"</td>" +

"<td>"+res[i].leagueName.highlight(keyword)+"</td>" +

"<td>"+res[i].homeTeam.highlight(keyword)+"</td>" +

"<td>"+res[i].awayTeam.highlight(keyword)+"</td>" +

"<td><button type='submit' id="+res[i].eventId+">delete</button></td>" +

"</tr>");

}

},

error : function(err) {

console.log(err);

}

});

});

});

你可能感兴趣的:(关键字)