Angularjs Realizes Highlighting of Search Keywords
- 2021-07-12 04:49:20
- OfStack
Requirements analysis:
Search Web page content by keywords and highlight keywords in the content
Detail analysis:
1. Every time you perform a search operation, you need to empty the last result
2. It is necessary to distinguish html label from normal text content, otherwise the label content will be displayed after adding style to keywords
Code thinking:
Matching Keywords with Regular Expressions
Use javascript string replacement to replace keywords with < span class='red' > Keyword < /span >
In order to avoid the occurrence when the keyword is' p ', the label < p > Replace with < < span > p < /span > > ... and so on
All match and replace operations are only for text nodes in the current DOM element, and all nodes are traversed through recursive functions
Front-end frame:
angularjs^1.2.9
$scope.myData = '<div>woshihight<h2>womei<b>bbb</b>shihigh<span>haha</span></h2><span>1000pxhight</span><ul><li>1high</li><li>2hight span light hight< p></li></ul><a href="index.html"> This is the link address hight</a></div>';
$scope.myDataCp = angular.copy($scope.myData);
$scope.key = '';
$scope.searchKey = function() {
if($scope.key != '') {
searchHighLight($scope.key);
}
}
function searchHighLight(key) {
var _element = angular.element($scope.myDataCp);
nodeRecursion(_element[0],key);
var _htmlStr = _element[0].innerHTML.toString();
_htmlStr = _htmlStr.replace(/_1000px_/g, '<span class="red">').replace(/_xp0001_/g, '</span>');
$scope.myData = _htmlStr;
}
// Loop through to replace all text node contents
function nodeRecursion(e, key) {
var reg = new RegExp(key, 'g');
var _count = e.childNodes.length;
for(var _i=0; _i < _count; _i++) {
if(e.childNodes.item(_i).nodeType == 3) {
var _str = e.childNodes.item(_i).data;
if(_str.indexOf(key)!=-1) {
_str = _str.replace(reg,'_1000px_'+key+'_xp0001_');
}
e.childNodes.item(_i).data = _str;
} else {
nodeRecursion(e.childNodes.item(_i), key);
}
}
}
Other notes:
searchKey//Click the search button to call this method
The html string in $scope. myData must have 1 root node, such as div here
Loading the html field in the html page requires the ng-bind-html instruction, which requires loading the ngSanitize module