Make onKeyDown trigger an HTML button's onClick event

你。 提交于 2020-01-17 07:08:30

问题


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.

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>

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.


回答1:


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.

with jQuery your code would look something like this

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

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
 });


来源:https://stackoverflow.com/questions/10355895/make-onkeydown-trigger-an-html-buttons-onclick-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!