javascript cross browser scripting help
I have a tiny function I use to only allow numeric input. It works great in IE, but I cannot get it to work in FireFox or Chrome. I have this js file loaded in my script tag of my HTML page.
var numberOnly = function(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
}
};
var wireElemToEvent = function(elemId, event, func){
var elem = document.getElementById(elemId);
if (typeof window.event !== 'undefined') {
elem.attachEvent("on" + event, func);
} else {
elem.addEventListener(event, func, true);
}
};
var wireEvents = function(){
wireElemToEvent("tbxQuantity", "keypress", numberOnly);
wireElemToEvent("tbxPhone", "keypress", numberOnly);
wireElemToEvent("tbxZip", "keypress", numberOnly);
};
window.onload = wireEvents;
Chrome tells me
file:///C:/Documents%20and%20Settings/xxx/Desktop/numbersonly/res/js/numbersonly.js:17Uncaught TypeError: Object # has no method 'attachEvent'
Any idea what I am doing wrong?
Thanks for any help, ~ck
In wireElemToEvent
You may want to check that elem
is not null after you initialize it. Also, it would be better to check the existence of elem.attachEvent
and elem.addEventListener
rather than whether window.event
is defined.
Here is the function I use to attach events cross browser:
function eventListen( t, fn, o ) {
o = o || window;
var e = t+fn;
if ( o.attachEvent ) {
o['e'+e] = fn;
o[e] = function(){
o['e'+e]( window.event );
};
o.attachEvent( 'on'+t, o[e] );
}else{
o.addEventListener( t, fn, false );
}
}
And to use it:
eventListen('message', function(e){
var msg = JSON.parse(e.data);
...
});
I've had the same problem and, because I am a novice, was looking around for a day for a solution. Apparently (typeof window.event !== 'undefined') doesn't stop Safari/Chrome from getting in that if statement. So it actually initializes the attachEvent and doesn't know what to do with it.
Solution:
var wireElemToEvent = function(elemId, event, func){
var elem = document.getElementById(elemId);
if (elem.attachEvent) {
elem.attachEvent("on" + event, func);
}
else { // if (elem.addEventListener) interchangeably
elem.addEventListener(event, func, true);
}
};
链接地址: http://www.djcxy.com/p/74150.html
上一篇: HTMLCollection和NodeList是否可迭代?
下一篇: JavaScript跨浏览器脚本帮助