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