javascript - 如何突出显示搜索结果的颜色
问题描述
你能帮忙突出显示黄色搜索的单词吗?
下面的代码示例已编写用于过滤来自 JSON 提要 URL 的显示数据中的单词。
angular.module('sample', []).
controller('sampleController', ['$scope', '$http', function($scope, $http) {
var url = "https://spreadsheets.google.com/feeds/list/153Obe1TdWlIPyveZoNxEw53rdrghHsiWU9l-WgGwCrE/od6/public/values?alt=json";
$http.get(url)
.success(function(data, status, headers, config) {
$scope.users = data.feed.entry;
console.log($scope.users);
})
.error(function(error, status, headers, config) {
console.log(status);
console.log("Error occured");
});
// code to highlight
$scope.highlight = () => {
//create copy of the original array
$scope.filteredContent = JSON.parse(JSON.stringify($scope.users));
$scope.filteredContent.forEach(fc => {
const regEx = new RegExp($scope.search);
alert("here");
fc.question = fc.gsx$topic.$t.replace(regEx, '<span class="highlight">${$scope.search}</span>');
fc.answer = fc.gsx$response.$t.replace(regEx, '<span class="highlight">${$scope.search}</span>');
});
};
// code to highlight
$scope.search='';
$scope.searchFilter=function(item){
if(item.gsx$topic.$t.toLowerCase().indexOf($scope.search.toLowerCase()) != -1 || item.gsx$response.$t.toLowerCase().indexOf($scope.search.toLowerCase()) != -1){
return true;
}
return false;
}
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.0/angular.min.js"></script>
<div ng-app="sample" ng-controller="sampleController">
<div class="black">
<input type="text" name="search" ng-keyup="highlight()" ng-model="search" placeholder="search"/>
</div>
<br>
<br>
<br>
<table style="border: 1px solid black ;">
<tbody>
<tr>
<td>
<center><b>Question</b></center>
</td>
<td>
<center><b>Response</b></center>
</td>
</tr>
<tr ng-repeat="user in users | filter:searchFilter">
<td style="border: 1px solid black ; width:30%;white-space: pre-wrap;" ng-bind-html="user.gsx$topic.$t">{{user.gsx$topic.$t}}</td>
<td style="border: 1px solid black ; width:70%;white-space: pre-wrap;" ng-bind-html="user.gsx$response.$t">{{user.gsx$response.$t}}</td>
</tr>
</tbody>
</table>
</div>
解决方案
您需要使用$sce
服务Strict Contextual Escaping。
在您的控制器声明中添加此服务,如下所示:
controller('sampleController', ['$scope', '$http', '$sce', function($scope, $http, $sce) {
现在你必须定义一个函数,它只会注入一个span
带有黄色突出显示的 CSS 类名的标签,当找到搜索到的文本时,通过该$sce.trustAsHtml
方法指示 AngularJS,注入的是安全内容。
$scope.highlightText = function(text, search) {
if (search && search.length === 0) {
// Returns the default content.
return $sce.trustAsHtml(text);
}
// Define a regular expression to find the text globally and ignoring capital letters.
var regex = new RegExp(search, 'gi');
// If you already found the text then inject a span element with CSS class to highlight that you found.
return $sce.trustAsHtml(text.replace(regex, '<span class="foundText">$&</span>'));
};
在前面的正则表达式替换文本中,$&
表示显示与替换中的正则表达式匹配的捕获文本。
在 HTML 中,在 中ng-repeat
添加ngBindHtml
指令 withhighlightText
函数,其中第一个参数是您必须搜索的文本,第二个参数是要查找的文本。
在您的情况下,以这种方式:
<tr ng-repeat="user in users | filter:searchFilter">
<td style="border: 1px solid black ; width:30%;white-space: pre-wrap;" ng-bind-html="highlightText(user.gsx$topic.$t, search)">{{user.gsx$topic.$t}}</td>
请参阅此示例:
angular.module('sample', []).
controller('sampleController', ['$scope', '$http', '$sce', function($scope, $http, $sce) {
var url = "https://spreadsheets.google.com/feeds/list/153Obe1TdWlIPyveZoNxEw53rdrghHsiWU9l-WgGwCrE/od6/public/values?alt=json";
$http.get(url)
.success(function(data, status, headers, config) {
$scope.users = data.feed.entry;
console.log($scope.users);
})
.error(function(error, status, headers, config) {
console.log(status);
console.log("Error occured");
});
$scope.search = '';
$scope.searchFilter = function(item) {
if (item.gsx$topic.$t.indexOf($scope.search) != -1 || item.gsx$response.$t.indexOf($scope.search) != -1) {
return true;
}
return false;
};
$scope.highlightText = function(text, search) {
if (search && search.length === 0) {
// Returns the default content.
return $sce.trustAsHtml(text);
}
// Define a regular expression to find the text globally and ignoring capital letters.
var regex = new RegExp(search, 'gi');
// If you already found the text then inject a span element with CSS class to highlight that you found.
return $sce.trustAsHtml(text.replace(regex, '<span class="foundText">$&</span>'));
};
}]);
.foundText {
background-color: #ff0;
color: #f00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.0/angular.min.js"></script>
<div ng-app="sample" ng-controller="sampleController">
<div class="black">
<input type="text" name="search" ng-model="search" placeholder="search" ng-click="didSelectLanguage()" />
</div>
<br>
<br>
<br>
<table style="border: 1px solid black ;">
<tbody>
<tr>
<td>
<center><b>Question</b></center>
</td>
<td>
<center><b>Response</b></center>
</td>
</tr>
<tr ng-repeat="user in users | filter:searchFilter">
<td style="border: 1px solid black ; width:30%;white-space: pre-wrap;" ng-bind-html="highlightText(user.gsx$topic.$t, search)">{{user.gsx$topic.$t}}</td>
<td style="border: 1px solid black ; width:70%;white-space: pre-wrap;" ng-bind-html="highlightText(user.gsx$response.$t, search)">{{user.gsx$response.$t}}</td>
</tr>
</tbody>
</table>
</div>
希望这可以帮助!
推荐阅读
- spark-java - 将 spark-java 请求转发到另一个资源
- dart - 如何检查 Flutter Text 小部件是否溢出
- julia - 在 Julia 中将函数参数更改为关键字似乎会引入类型不稳定性
- asynchronous - 如何将迭代器转换为成功时的流或失败时的空流?
- javascript - 使用Javascript将对象数组转换为对象
- npm - 如何在 npm 脚本中更喜欢全局 npm 而不是本地 npm?
- javascript - 如何在单击时更改具有一个 id 的多个按钮类?
- go - 带有 go 和 dep 的 Heroku:`推送被拒绝:无法编译 Go 应用程序`
- python - 对单词进行计数和排序时,带有大 .txt 文件 Python 的 MemoryError
- jquery - jQuery:仅当用户输入正确的字符串格式时才启用提交按钮