JavaScript无法在Firefox中运行

时间:2010-02-19 15:21:32

标签: javascript

嗨'我在firefox中遇到我的脚本问题,我遇到了错误,“window.event未定义”,这似乎是问题所在?

<script language="JavaScript1.2"> 

function formattel(){

 var value = document.formkkush.telefoon.value; 
 var valueLen = document.formkkush.telefoon.value.length; 

 if(valueLen>2 && valueLen<4) 
 { 
 if(window.event.keyCode==8) 
 document.formkkush.telefoon.value=document.formkkush.telefoon.value.remove(valueLen-1,1); 
 else 
 document.formkkush.telefoon.value=document.formkkush.telefoon.value+"/"; 
 }
 if(valueLen>5 && valueLen<7) 
 { 
 if(window.event.keyCode==8) 
 document.formkkush.telefoon.value=document.formkkush.telefoon.value.remove(valueLen-1,1); 
 else 
 document.formkkush.telefoon.value=document.formkkush.telefoon.value+"."; 
 }
 if(valueLen>8 && valueLen<10) 
 { 
 if(window.event.keyCode==8) 
 document.formkkush.telefoon.value=document.formkkush.telefoon.value.remove(valueLen-1,1); 
 else 
 document.formkkush.telefoon.value=document.formkkush.telefoon.value+"."; 
 }
} 

2 个答案:

答案 0 :(得分:3)

不在Firefox中创建全局事件对象。它被作为事件处理程序函数中的第一个参数传递。

function formattel(eventObj){ 
  var value = document.formkkush.telefoon.value;  
  var valueLen = document.formkkush.telefoon.value.length;  

  // Make sure we have the even object no matter which browser we're running on
  eventObj = eventObj || window.event;

  if(valueLen>2 && valueLen<4)  
  {  
    if(eventObj.keyCode==8)  
      document.formkkush.telefoon.value=document.formkkush.telefoon.value.remove(valueLen-1,1);  
    else  
      document.formkkush.telefoon.value=document.formkkush.telefoon.value+"/";  
  } 
  // etc...
}  

请参阅event的Mozilla文档。

作为一个完全不相关的建议,您应该尝试通过设置对变量的重复查找来减少DOM节点查找的数量。它使您的代码更快,更易于呈现:

function formattel(eventObj){ 

  var telefoon = document.formkkush.telefoon; 
  var value = telefoon.value;  
  var valueLen = value.length;  

  // Make sure we have the even object no matter which browser we're running on
  eventObj = eventObj || window.event;

  if(valueLen>2 && valueLen<4)  
  {  
    if(eventObj.keyCode==8)  
      telefoon.value = telefoon.value.remove(valueLen-1,1);  
    else  
      telefoon.value += "/";  
  } 
  // etc...
}  

不要忘记赋值运算符(例如+=)!

答案 1 :(得分:0)

似乎很多人都面临这个问题。你有check this post吗?