我正试图在网页上突出显示搜索到的文字。我以json响应的形式从服务器获取内容到网页。在JSON响应中。我得到两个HTML响应与标签和非HTML响应。在我的HTML响应。有很多span标签是用空span标签拆分单个词的。例如:“搜索文本”的格式为“ <span class="c1">Sea</span>rch<span class="c2">text</span>
”。分词在接收到的词语响应中的各个位置发生。
我正在使用角度高光。“ angular-highlight ”突出显示未被html标签分割的单词。如果单词被分割,它不会突出显示。但是,它仍然不起作用。
<span>Sample</span>
- 将突出显示
<span>Sa<span>mp</span>le</span>
- 不会突出显示
<span>Sa<span></span>mple<span></span></span>
- 不会突出显示
我也使用了trustAsHtml方法。但是,它不工作。
发布于 2018-05-31 09:51:08
代码:
angular.module('angular-highlight', []).directive('highlight', function() {
var matchCount = 0;
var newCheckKeyword = '';
var component = function(scope, element, attrs) {
if (!attrs.highlightClass) {
attrs.highlightClass = 'angular-highlight';
}
var count = 0;
var replacer = function(match, item) {
count++;
var temp = matchCount+count;
return '<span class="'+attrs.highlightClass+'" id="highlightId'+temp+'">'+match+'</span>';
}
var tokenize = function(keywords) {
keywords = keywords.replace(new RegExp('^ | $','g'), '');
return keywords;
}
scope.$watch('keywords', function(newKeyword, oldKeyword) {
if(newCheckKeyword == '' || newCheckKeyword != newKeyword){
newCheckKeyword = newKeyword;
matchCount = 0;
count = 0;
scope.sendCount({count: matchCount});
}
//console.log("scope.keywords",scope.keywords);
if (!scope.keywords || scope.keywords == '') {
element.html(scope.highlight);
return false;
}
var tokenized = tokenize(scope.keywords);
// Modified to skip HTML tags
var regex = new RegExp(tokenized+'(?!([^<]+)?>)', 'gmi');
// Find the words
var html = scope.highlight.replace(regex, replacer);
//var htmlCount = scope.highlight.match(regex, replacer);
element.html(html);
matchCount = matchCount+count;
scope.sendCount({count: matchCount});
count = 0;
});
}
return {
link: component,
replace: false,
scope:{
highlight:'=',
keywords:'=',
sendCount:'&'
}
};
});
https://stackoverflow.com/questions/-100004629
复制相似问题