如何在不使用按钮的情况下搜索任何单词并将其突出显示?

时间:2019-04-08 08:55:23

标签: javascript jquery razor

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

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

1 个答案:

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