问题
I have got the following sample, that easily detects the "Enter" key pressing and handles it correctly. Here it is:
<!DOCTYPE html>
<html>
<head>
<title>keyCode example</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#search-input").keyup(function (event) {
event = event || window.event;
if (event.keyCode == 13 || event.which == 13) {
$("#search-button").click();
}
});
$("#search-button").click(function () {
var theUrl = "http://www.yahoo.com/"
window.location = theUrl;
});
});
</script>
</head>
<body>
<input id="search-input" name="search" type="text"/>
<button id="search-button" type="button" alt="Search">Search</button>
</body>
</html>
This really works for me in every popular browser.
The problem is this code does not work on my production environment in any browser except Firefox.
On my production environment the script is also built in into the $(document).ready
function and located in separate "main.js" file. The debug mode showed, that when I enter letters or numbers in the text field the script is running correctly. When I press the "Enter" key, the program does not even go into $("#search-input").keyup(function (event){
section. But the text disappears from the text field, it seems that page reloads.
I repeat one more time, that the problem can be reproduced only on production site. On separate local page, that I showed above, everything works fine.
Does anyone know what is the problem?
Update: All the keys are handling normally, except Enter. When I press Enter, $("#search-input").keyup(function (event){
doesn't run, like no events happened.
回答1:
The problem is solved using the following code for handling pressing the "Enter" key:
$("#search-button").on('click', function () {
var theUrl = "/search.aspx?search=" + $('#search-input').val();
window.location = theUrl;
});
$('#search-input').on('keyup', function (e) {
if (e.which == 13)
$("#search-button").trigger('click');
});
This code is built into the $(document).ready
function.
来源:https://stackoverflow.com/questions/14922266/cross-browser-handling-the-enter-key-pressing-using-javascript