Jquery Keyup() example not working on server
I am trying to use the keyup function in a little search I made, but with the files on the server and accessing the page through IE8 and FF, the keyup function doesn't seem to work. To test it I borrowed the code from the jQuery websites example put it on the server (it's Windows Server 2003 R2). However, this example also isn't working(http://api.jquery.com/keyup/). I noticed it has the line
开发者_如何学C<script type="text/javascript" src="/scripts/events.js"></script>
and my initial thought was, "mine isn't working because I'm missing this events file!" but after googling I'm thinking this isn't the case. In my code I'm linking to a downloaded copy of jQuery, and I've also tried linking it through the googleapi's copy, no luck either time. Any thoughts about why the keyup function might not be working on the server?
The code on that page seems a little broken. Specifically, it seems to use a print
function that's absent from the latest jQuery (perhaps it's included in that missing events.js
script?)
I've made some small changes to make a working version (note I'm using the Google-hosted jQuery; you can point that at your local version instead and it should still work fine.)
<!DOCTYPE html>
<html>
<head>
<style>
fieldset { margin-bottom: 1em; }
input { display: block; margin-bottom: .25em; }
#print-output {
width: 100%;
}
.print-output-line {
white-space: pre;
padding: 5px;
font-family: monaco, monospace;
font-size: .7em;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
</head>
<body>
<form>
<fieldset>
<label for="target">Type Something:</label>
<input id="target" type="text" />
</fieldset>
</form>
<button id="other">
Trigger the handler
</button>
<div id="output"></div>
<script>
var xTriggered = 0;
$('#target').keyup(function(event) {
if (event.keyCode == '13') {
event.preventDefault();
}
xTriggered++;
var msg = 'Handler for .keyup() called ' + xTriggered + ' time(s).<br />';
$('#output').append(msg);
});
$('#other').click(function() {
$('#target').keyup();
});</script>
</body>
</html>
In this changed version, I'm using jQuery's append()
function to output the debugging messages into a new div
I've added below the text box. When you type into the text box, you should see the key press events being registered there.
Does the element you're watching get generated dynamically, after page load? If so you'll need to use live:
$("#element").live('keyup',function(e) {
var keycode = e.keyCode ? e.keyCode : e.which;
});
Otherwise try:
$("element").keyup(function(e) {
var keycode = e.keyCode ? e.keyCode : e.which;
});
Also, make sure you are selecting the proper element (input box?) and double check the selector is correct. Some problems might arise in different browsers, handling e.keyCode, or not. The above example also checks for a key code value in e.which, if e.keyCode does not exist.
精彩评论