Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
774 views
in Technique[技术] by (71.8m points)

internet explorer - Javascript: IE event.preventDefault is null or not an object

My code works fine in FF/Chrome/Everything except IE(failed in both 7/8, didn't bother going furthur down). Due to restrictions, I cannot use jQuery and am hard-coding the Javascript. The issue is with IE, I am getting "preventDefault is null or not an object". Hoping one of you has the answer, and here's relevant code:

AddEvent Method:

function addEvent( obj, type, fn ) {  
  if ( obj.attachEvent ) {  
    obj['e'+type+fn] = fn;  
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}  
    obj.attachEvent( 'on'+type, obj[type+fn] );  
  } else  
    obj.addEventListener( type, fn, false );  
};

Event handler throwing error:

function mousedown(e){  
  if(e.preventDefault){  
    e.preventDefault();  
  } else {  
    e.returnValue = false;  
    e.cancelBubble=true;  
  }
  //Processing   
};

Also DOCTYPE and charset are both set on the calling HTML page. Any ideas would be appreciated. The error is thrown in the if statement for the mousedown method.

EDIT:

Due to the fact that grabbing window.event did "fix" the main issue, I discovered the problem was a different section of code. Basically I am adding a element ontop of a pre-placed element, and then registering mousedown/mousemove events to that div. When firing the event on the <div>, THAT'S where the error is thrown.

Could this be something due to the fact that I have events registered to 2

rect = document.createElement('div');  
rect.className='square';  
rect.id='chooser_rectangle';  
rect.style.left=initx+'px';  
rect.style.top=inity+'px';  

addEvent(rect,"mousemove",mousemove);  
addEvent(rect,"mousedown",mousedown);  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In IE the event object is not passed as the first argument to an event handler. Instead it is a global variable:

function mousedown(e){
 var evt = e || window.event; // IE compatibility
 if(evt.preventDefault){  
  evt.preventDefault();  
 }else{  
  evt.returnValue = false;  
  evt.cancelBubble=true;  
 }
 //Processing   
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...