2013-03-22 30 views
0

我想用正则表达式监视charector。e.keycode在firefox 19.0.2中未定义,chrome 25.0.1364.172 m,IE 8

$('#searchContent').keyup(function(e){ 

     e = e || window.event; 

     var patt =/\w/g; 
     var key = String.fromCharCode(e.keyCode); 


     console.log ("key " + key + e.keycode+ " is pressed!!"); 

     if(e.keycode != 8 && e.keyCode != 46){ //Will return if printable char is not typed. But the datagrid will still refresh on pressing backspace. 
      console.log ("key " + key+ e.keycode + "is about to take test!!"); 
      if(!patt.test(key)){ 
       console.log ("key " + key+e.keycode + "is failed!!"); 
       return; 
      } 
      console.log ("key " + key +e.keycode+ "is pressed passes the test!!"); 
     } 
     else{ 
      console.log ("backspace or delete has ByPasses the conditoin!!"); 
     } 
      // other operations.... 
} 
    //Result of my log. INPUT : RIS(<-backspace) 
    key R undefined is pressed!! index_tab.php:173 
    key R undefined is about to take test!! index_tab.php:176 
    key R undefined is pressed passes the test!! index_tab.php:181 
    key I undefined is pressed!! index_tab.php:173 
    key I undefined is about to take test!! index_tab.php:176 
    key I undefined is pressed passes the test!! index_tab.php:181 
    key S undefined is pressed!! index_tab.php:173 
    key S undefined is about to take test!! index_tab.php:176 
    key S undefined is pressed passes the test!! index_tab.php:181 
    key undefined is pressed!! index_tab.php:173 //here backspace was pressed 
    key undefined is about to take test!! index_tab.php:176 
    key undefined is failed!! 
+0

案例是敏感这里,MHM。 – jolt 2013-03-22 09:03:03

+0

'e.which'在jQuery中被标准化,所以大多数人都使用它! – adeneo 2013-03-22 09:05:16

回答

7

总之,JavaScript的区分大小写。

e.keycode != e.keyCode

而且,你应该使用camelCase倒是一个 - e.keyCode

假设$标志是jQuery的,我建议查找代码,当您使用e.which。它已被标准化为与每个浏览器兼容。

在这里看到:http://api.jquery.com/event.which/,基本上in source is

// Add which for key events 
if (event.which == null) { 
    event.which = original.charCode != null ? original.charCode : original.keyCode; 
} 
+0

如果您赞成,请提供评论和理由,谢谢。 – jolt 2013-03-22 09:12:48

相关问题