将参数传递给KeyDown [英] Passing Parameters to KeyDown

查看:127
本文介绍了将参数传递给KeyDown的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从jquery将参数传递到keydown方法中,因为每当我使用在其他地方定义的变量时,它都会返回未定义的值.我以为它是因为#target是窗口,因此它不在范围内,但是即使那样,我仍然很难使它将key.which()与外部参数进行比较,然后将其分配给另一个属性.

How can you pass parameters into the keydown method from jquery because whenever I use a variable defined elsewhere it returns undefined. I assume its because the #target is window and therefore its not in the scope but even then I have trouble getting it to compare the key.which() with an outside parameter and then assigning it to another property.

示例:

var a = 38;
var b = 0;
$(document).keydown(function(e){
  var key = e.which;
  if (a==key)
    b=key;
});
console.log(a+""+b);

每当我尝试执行相同操作时,它会返回38 0,我将其解释为不在范围内且未定义(这也是因为如果我登录b,它将在keydown函数中打印未定义)?我怎样才能通过?

Whenever I try to do something along the same lines it returns 38 0 which I interpreted as it not being in the scope and being undefined (also because if I log b it prints undefined in the keydown func)? How could I pass in a?

推荐答案

console.log无法正常工作,因为它在脚本加载时已初始化.您需要做的就是在按下该键时触发功能.

You console.log is not working because it is initialized when the script load. What you need to do is to trigger your functions when the key is pressed.

// When the document is ready
$(function() {
   $(document).keydown(function(e){
      var key = e.which;
      var a = 'a scoped variable';
      switch (key) {
          // Up arrow
          case 38: 
             a = upArrowFunction(a); // Assign a to the returned value.
             break;
          // Down arrow
          case 40:
             downArrowFunction();
             break;
      }

   });

   function upArraowFunction(a) {
       a = 'I change a, but a is not changed in keydown event';
       return a; // But now I return the changed variable so it will change if a variable is assigned where the function is called.
   }

   function downArrowFunction() {
       // Do something else
   }
});

这篇关于将参数传递给KeyDown的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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