JavaScript: How to highlight text with pressing “Enter/Return”?

走远了吗. 提交于 2019-12-13 04:23:57

问题


I'm trying to create a functioning search box that highlights words in a text. However, I cannot make it do the search by pressing Enter. Do you have any suggestions where is the flaw in the code? Thanks!

HTML:

<form>
<input type="text" id="search" onkeypress="if (e.keycode==13) doSearch(document.getElementById('search').value)" placeholder="What are you looking for?">
</form>

JavaScript:

function doSearch(text)
{
if (window.find && window.getSelection)
   {
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
while (window.find(text))
      {
document.getElementById("search").blur();
document.execCommand("HiliteColor", false, "green");
sel.collapseToEnd();
      }
document.designMode = "off";
   }
else if (document.body.createTextRange)
   {
var textRange = document.body.createTextRange();
while (textRange.findText(text))
      {
textRange.execCommand("BackColor", false, "green");
textRange.collapse(false);
      }
   }
}

回答1:


Try like this instead

  <input type="text" id="search" onkeypress="if (window.event.keyCode==13) doSearch(this.value);" placeholder="What are you looking for?">

No need to use document.getElementbyId() as you are in the textbox, simply do this.value.

Fiddle DEMO




回答2:


change your event trigger to read as the following

<input type="text" id="search" onkeypress="if (window.event.keyCode==13) doSearch(document.getElementById('search').value)" placeholder="What are you looking for?">

i also recommend using onkeydown instead of onkeypress because onkeypress doesn't detect certain control keys being pressed.




回答3:


Can you use jQuery for this? Starts to tidy up the code somewhat, and moves your javascript out of the view.

$('#search').keypress(function(e) {
  if (e.keyCode == '13') {
     e.preventDefault();
     doSearch(this.value);
   }
});


来源:https://stackoverflow.com/questions/17548454/javascript-how-to-highlight-text-with-pressing-enter-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!