我有一个搜索功能,可以搜索所有输入的单词。如果单击搜索按钮,该函数将运行。我在下面的代码中为其创建了函数。我想要的是进行搜索而不使用实时搜索之类的按钮。 有什么想法吗?谢谢
<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>
答案 0 :(得分:0)
您可以使用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>