使onKeyDown触发HTML按钮的onClick事件 [英] Make onKeyDown trigger an HTML button's onClick event

查看:148
本文介绍了使onKeyDown触发HTML按钮的onClick事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Calculator的基本HTML表单,带有一个名为"btnOne"的按钮.我想要的是当用户按下键盘上的"1"键时,发生"btnOne" HTML按钮的onClick事件.

I have a basic HTML form named Calculator, with a button named "btnOne". What I want is for when the user presses the "1" key on the keyboard, the "btnOne" HTML button's onClick event to occur.

为尝试实现此目的,我将此函数放置在文档的Head标签中:

To attempt to accomplish this, I placed this function in the Head tag of my document:

<head>
     <SCRIPT LANGUAGE="JavaScript"> 

         //other functions...

        document.onkeydown = function(e){
            if (!e) e = window.event;
            if(e.keycode == '49') {
                document.Calculator.btnOne.click();
            }
            return false;
        }
      </SCRIPT>
</head>

我只是将这段代码放在错误的位置吗?我还需要做些其他的事情才能使函数运行吗?我真的是Web开发的初学者,不知道我在做什么!当然,一旦我弄清楚如何使此按钮起作用,我将为所有其他按钮添加if语句.

Am I just putting this snippet in the wrong spot? Is there something else I need to do to make the function run? I'm really a beginner with web development and don't know what I'm doing! Of course, once I get figured out how to get this button to work, I will add if statements for all of the other buttons.

推荐答案

签出 http://api .jquery.com/category/events/,以更轻松,更简洁的方式编写代码.您拥有的基本上是正确的,尽管您最好将其包装在文档就绪事件中,以使事件在dom加载后 绑定.

check out http://api.jquery.com/category/events/ for a much easier and cleaner way to write this. What you have is basically right, though you'd do well to wrap this in a document ready event, so that the events bind after the dom has loaded.

使用jQuery,您的代码将如下所示

with jQuery your code would look something like this

jQuery(function() {
    jQuery(window).keypress(function(e){
         if (e.which === 49) {
               jQuery("#btnOne").click();
         }
    });
})

这里有一个工作的JS小提琴,将对此进行演示

heres a working JS Fiddle that will demonstrate this

http://jsfiddle.net/HXYAD/

但是,将点击的事件处理程序抽象到参数化函数中可能是个好主意,这样您就不必

However, its probably a good idea to abstract out the event handler for the click into a parameterized function so that you dont have

 jQuery('#btnOne').click(function(){
     //some code
 });

 jQuery('#btnTwo').click(function(){
     //some similar code
 });     
 jQuery('#btnThree').click(function(){
     //some more similar code
 });

这篇关于使onKeyDown触发HTML按钮的onClick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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