Javascript:IE event.preventDefault为null或不是对象 [英] Javascript: IE event.preventDefault is null or not an object

查看:100
本文介绍了Javascript:IE event.preventDefault为null或不是对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码在FF / Chrome / Everything中运行良好,除了IE(7/8都失败了,没有打算继续下去)。由于限制,我不能使用jQuery并且硬编码Javascript。问题出在IE上,我得到preventDefault为null或者不是对象。希望你们其中一个人有答案,这里是相关代码:

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方法:

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   
};

此外,DOCTYPE和charset都在调用HTML页面上设置。任何想法,将不胜感激。错误在mousedown方法的if语句中抛出。

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.

编辑:

由于这一事实抓住window.event确实修复了主要问题,我发现问题是代码的不同部分。基本上我在预先放置的元素的ontop上添加一个元素,然后将mousedown / mousemove事件注册到该div。在< div> 上触发事件时,就会发生错误。

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.

这可能是什么由于我已将事件注册到2

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);  


推荐答案

在IE中,事件对象不作为第一个传递事件处理程序的参数。相反,它是一个全局变量:

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   
};

这篇关于Javascript:IE event.preventDefault为null或不是对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆