The example in this article describes how jquery implements page keyword highlighting. Share it with everyone for your reference. The specific analysis is as follows:
Highlight page search keywords through jquery
Support highlighting in Chinese multi-word pages
1. The JavaScript code is as follows:
jQuery.fn.extend({
Highlight: function(search, configs){
If(typeof(search) == 'undefined') return;
var configs = jQuery.extend({
insensitive: 1, //Whether to match upper and lower case 0 matches 1 does not match
hls_class: 'highlight', // Highlighted class
clear_last: true, // Clear the original highlighted results
},configs);
if(configs.clear_last) {
$(this).find("strong." configs.hls_class).each(function(){
$(this).after($(this).text());
$(this).remove();
})
}
return this.each(function() {
If(typeof(search) == "string") {
$(this).highregx(search,configs);
} else if (search.constructor === Array) {
for(var query in search){
var search_str = $.trim(search[query]);
If(search_str != "") $(this).highregx(search_str,configs);
}
}
});
},
Highregx: function(query,configs){
query = this.unicode(query);
var regex = new RegExp("(<[^>]*>)|(" query ")", configs.insensitive ? "ig" : "g");
This.html(this.html().replace(regex, function(a, b, c){
return (a.charAt(0) == "<") ? a : "" c "";
}));
},
unicode: function(s){
var len=s.length;
var rs="";
s = s.replace(/([-.* ?^${}()|[]/\])/g,"\$1");
for(var i=0;i
If(s.charCodeAt(i) > 255)
rs ="\u" s.charCodeAt(i).toString(16);
else rs = s.charAt(i);
return rs;
}
});
2. Click here to download the highlight plug-in
.
I hope this article will be helpful to everyone’s jQuery programming.
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn