开发者

jQuery/JS Keycodes: Several keycodes in one IF statement

I'm trying to set up some keycodes for an app I'm working on but it really drives me crazy.

I'm trying to set up keycodes which would say, from keyCode 65 to 91 , 44 , 47 and few others, do function.

So I have this:

var e = event || evt;
if ((e.keyCode > 65 || e.Keycode < 91)){
    // Do function
}

which works find. Now if I try to add another keycode it doesn't work. This is what I tried:

if ((e.keyCode > 65 || e.Keycode < 91) &a开发者_Python百科mp;& (e.keyCode == 44) && (e.keyCode == 47)){

Does someone help me to add different keycodes in one If statement?

Thanks alot


Try this

if (
  // get all the keys between 65-90
  (e.keyCode >= 65 && e.keyCode <= 90) 
  // or  44 or 47
  || e.keyCode == 44 || e.keyCode == 47)
{
   // do stuff
}

If the conditional logic is tripping you up, I think you might be best served by thinking about the numbers you want to include (not exclude). Break them into ranges and put each range on its own line. Start with pseudo code:

if 
  // keys between 31-47
  // or keys between 58-90
then
  // do stuff
end

Then fill in the conditions:

if (
  // keys between 31-47
  (e.keyCode >= 31 && e.keyCode <= 47) 

  // or keys between 58-90
  || (e.keyCode >= 58 && e.keyCode <= 90) 
)
{
  // do stuff
}


If you want everything from 31 to 90 except for those from 48 through 57:

if (e.keyCode >= 31 && e.keyCode <= 90 && !(e.keyCode >= 48 && e.keyCode <= 57)) {
  // whatever 
}

Now that could be written equivalently as:

if (e.keyCode >= 31 && e.keyCode <= 47 || e.keyCode >= 58 && e.keyCode <= 90) {
  // whatever
}


if ((e.keyCode > 65 && e.Keycode < 91) || e.keyCode == 44 || e.keyCode == 47){
   //do stuff
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜