javascript - 带有jquery的Javascript高亮功能不起作用
问题描述
我正在尝试使用 jQuery 构建一个“简单”的突出显示功能。出于某种原因,它使我的 HTML 重复,我不知道为什么。我想做的就是在搜索栏中输入搜索文本,并在我输入时突出显示标签中的文本。
有什么想法吗?绝望的...
这是HTML和JS
function hiLite(searchWords) {
if (searchWords) {
var content = $("p").text();
var regExp = new RegExp(searchWords, "ig");
var matches = content.match(regExp);
if (matches) {
$("p").html(content.replace(regExp, function(match) {
return "<span class='highlight'>" + match + "</span>";
}));
} else {
$(".highlight").removeClass("highlight");
}
} else {
$(".highlight").removeClass("highlight");
}
};
$("#searchBar").keyup(function() {
var userInput = $(this).val().toLowerCase();
hiLite(userInput);
});
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="photo_filter.css" type="text/css">
</head>
<body>
<div class="search">Search:
<input type="text" id="searchBar">
</div>
<div id="results">
<p>some text is here</p>
<p>other kinds</p>
<p>even more</p>
</div>
</body>
</html>
解决方案
解决方案2:
添加了基于搜索文本突出显示文本的条件
JS代码:
function hiLite(searchWords){
if(searchWords){
var content = $("p").text();
var regExp = new RegExp(searchWords, "ig");
var matches = content.match(regExp);
if(matches){
$('#results p').each(function() {
var test = '<span class="highlight">'+searchWords+'</span>';
var text = $(this).text();
$(this).html(text.replace(regExp, test));
});
}
}
};
$("#searchBar").keyup(function(){
var userInput = $(this).val().toLowerCase();
hiLite(userInput);
});
HTML 代码:
<div class="search">Search:
<input type="text" id="searchBar">
</div>
<div id="results">
<p>some text is here</p>
<p>other kinds</p>
<p>even more</p>
</div>
CSS:
.highlight{
color:red
}
JSF中:
推荐阅读
- c - rtspsrc 内部数据流错误 gstreamer c-appliaction
- mysql - 如果完整日期小于恢复日期,如何编写单个语句来检索用户观看视频的最后恢复?
- c++ - 树递归无限进行
- python - 自动化我创建 virtualenv 和 django 的任务
- java - 为什么子类对象引用父类值
- laravel - 当我使用 laravel 重新加载页面时,我想显示第一类产品?
- r - 有没有办法在 R 中将变量存储为数字但显示为 date9 格式?
- c# - 如何抑制用户对 ListBox 控件的操作
- angular - 如何在ag-grid中将特定列的部分标题名称更改为小写
- python - pd.ExcelWriter,追加日期时间但得到:未知或不支持的日期时间类型