首页 > 解决方案 > 如何在不使用按钮的情况下搜索任何单词并突出显示它?

问题描述

我有一个搜索功能,可以搜索所有输入的单词。如果单击搜索按钮,该函数将运行,我在下面的代码中为它创建了一个函数。我想要的是在不使用实时搜索之类的按钮的情况下进行搜索。有什么想法吗?谢谢

<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>

标签: javascriptjqueryrazor

解决方案


您可以使用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>


推荐阅读