The onKeyUp
event is working in IE(7) and not in Firefox(4.0.1).
I have a textfield with attribute onclick="eventName();"
in the Javascript function eventName(evt)
. I do not have an event data, the event data is not sent by Fi开发者_如何学JAVArefox. In IE on the other hand window.event
IS filled so here it works...
Both IE and Firefox reach the function just fine. Only problem is that I need the event data there. Can anyone direct me towards a solution for this annoying problem?
Example page:
<html>
<head>
<script type="text/javascript">
function upperCase(evt) {
if (evt) {
var target = evt.target;
target.value = target.value.toUpperCase();
} else if (window.event) {
var target = window.event.srcElement;
target.value = target.value.toUpperCase();
} else alert('No event information');
}
</script>
</head>
<body>
<span>Enter your name: </span>
<input type="text" id="fname" onkeyup="upperCase()" />
</body>
</html>
IE handles events with a global. Everything else the event passed as the first argument to the function.
onkeyup="upperCase()"
You don't do anything with it in there. I'm not even sure you can — I haven't touched an intrinsic event attribute for anything but the most trivial toy in years.
Given
document.getElementById('fname').keyup = upperCase;
(or, better, using attachEvent / addEvent, the evt
variable will be populated.)
To make this work in all browsers, pass the event
to the function you're calling:
<input type="text" id="fname" onkeyup="upperCase(event)">
function upperCase(evt) {
if (evt) {
var target = evt.target;
target.value = target.value.toUpperCase();
} else if (window.event) {
var target = window.event.srcElement;
target.value = target.value.toUpperCase();
} else alert('No event information');
}
<input type="text" id="fname" onkeyup="upperCase(event)">
In some browsers such as IE, this works because event
resolves to window.event
, which always refers to the current event being handled. In other browsers (such as Firefox), this works because event
is a variable that's in scope for the event handler. You can imagine the contents of the onkeyup
attribute as being the body of a function that looks like
function(event) {
// Attribute value here
}
You forgot to actually pass the event as parameter, should be:
<input type="text" id="fname" onkeyup="upperCase(event)" />
精彩评论