javascript - 如何在不使用按钮的情况下搜索任何单词并突出显示它?
问题描述
我有一个搜索功能,可以搜索所有输入的单词。如果单击搜索按钮,该函数将运行,我在下面的代码中为它创建了一个函数。我想要的是在不使用实时搜索之类的按钮的情况下进行搜索。有什么想法吗?谢谢
<style>
#search_para {
color: grey;
}
.highlight {
background-color: yellow;
}
</style>
<div id="wrapper">
<input type="text" id="search_text">
<input type="button" value="search" id="search">
</div>
<div id="inputText1">
<ul>
@Html.ActionLink("Form User", "Index", "User", null, new { @class = "btn btn-primary" })
@Html.ActionLink("Form Role", "Index", "Role", null, new { @class = "btn btn-primary" })
@Html.ActionLink("Form Transaction", "Index", "Transaction", null, new { @class = "btn btn-primary" })
</ul>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
var searchpara = document.getElementById("inputText1").innerHTML;
searchpara = searchpara.toString();
document.getElementById("search").onclick = function () { highlight_word(searchpara) };
}, false);
function highlight_word(searchpara) {
var text = document.getElementById("search_text").value;
if (text) {
var pattern = new RegExp("(" + text + ")", "gi");
var new_text = searchpara.replace(pattern, "<span class='highlight'>" + text + "</span>");
document.getElementById("inputText1").innerHTML = new_text;
}
}
</script>
解决方案
您可以使用onkeyup
它看起来像
document.getElementById("search_text").onkeyup = function() {
highlight_word(searchpara)
};
工作演示
document.addEventListener('DOMContentLoaded', function() {
var searchpara = document.getElementById("inputText1").innerHTML;
searchpara = searchpara.toString();
document.getElementById("search_text").onkeyup = function() {
highlight_word(searchpara)
};
}, false);
function highlight_word(searchpara) {
var text = document.getElementById("search_text").value;
if (text) {
var pattern = new RegExp("(" + text + ")", "gi");
var new_text = searchpara.replace(pattern, "<span class='highlight'>" + text + "</span>");
document.getElementById("inputText1").innerHTML = new_text;
}
}
#search_para {
color: grey;
}
.highlight {
background-color: yellow;
}
<div id="wrapper">
<input type="text" id="search_text">
</div>
<div id="inputText1">
<ul>
@Html.ActionLink("Form User", "Index", "User", null, new { @class = "btn btn-primary" }) @Html.ActionLink("Form Role", "Index", "Role", null, new { @class = "btn btn-primary" }) @Html.ActionLink("Form Transaction", "Index", "Transaction", null, new {
@class = "btn btn-primary" })
</ul>
</div>
推荐阅读
- node.js - 在 Node.js Express 中禁用 TLS 1.0 和 1.1 或仅使用 TLS 1.2 及更高版本
- javascript - React - 向下滚动页面时缩小导航图像
- java - 为我的所有 REST 控制器方法请求添加 @Around 建议后,不要返回任何 JSON 数据
- javascript - 为什么当 AST 已经知道该值时此代码返回 undefined
- mysql - MySQL ORDER BY 和 LIMIT 与存储过程中的变量
- go - 如何从 Cloud Run 访问其他 GCP 服务
- visual-studio-code - 查找并替换所有不在引号中的匹配项
- windows - 远程检索 Windows Defender 状态
- javascript - 使用 JavaScript 更新测验跟踪器答案 DIV
- python - 填充字典的输出与代码块中的打印语句不同