问题
I am using this function to handle enter click on a search textbox but it fires another button in the page, how to stop that button from being fired and call my search() function.
InputKeyPress(e) {
if (window.event) {
if (event.keyCode == 13) {
search();
}
} else {
if (e) {
if (e.which == 13) {
search();
}
}
}
}
回答1:
In the keyCode == 13
case, you need to prevent the default action of the keypress
event. The standard way to do this is to call the preventDefault
function on the event object (if it has one; it doesn't on earlier versions of IE). The older way is to return false
from your event handler function. There's no real harm in a "belt and braces" approach of doing both. :-)
You can also shorten your function a bit:
function InputKeyPress(e) {
var keyCode;
e = e || window.event;
keyCode = e.keyCode || e.which;
if (keyCode == 13) {
search();
if (e.preventDefault) {
e.preventDefault();
}
return false;
}
}
回答2:
You need to add "return false" like this:
function InputKeyPress(e) {
if (!e)
e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == 13) {
search();
return false;
}
return true;
}
And also change the call from the textbox to this:
<input .... onkeypress="return InputKeyPress(event);" ...>
Meaning not just call the function but "return" it.
来源:https://stackoverflow.com/questions/4237032/how-to-stop-a-button-from-being-fired-when-press-enter