简体   繁体   English

键盘输入,可在Javascript计算器上实现“全部清除”功能

[英]Keyboard input for a 'clear all' function on a Javascript calculator

I use this code for keyboard input on a calculator in Javascript. 我将此代码用于Javascript计算器上的键盘输入。 All the numbers and the decimal work, but the 'clear all' doesn't. 所有数字和小数均有效,但“全部清除”无效。 Does anyone have an idea why? 有谁知道为什么? Am I using a wrong ascii code? 我使用了错误的ASCII码吗?

//Add keyboard input
$(document).keypress(function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if (keycode === 49) {
        $("#one").click();
   } else if (keycode === 50) {
        $("#two").click();
    } else if (keycode === 51) {
        $("#three").click();
    } else if (keycode === 52) {
        $("#four").click();
    } else if (keycode === 53) {
        $("#five").click();
    } else if (keycode === 54) {
        $("#six").click();
    } else if (keycode === 55) {
        $("#seven").click();
    } else if (keycode === 56) {
        $("#eight").click();
    } else if (keycode === 57) {
        $("#nine").click();
    } else if (keycode === 48) {
        $("#zero").click();
    } else if (keycode === 127 || keycode === 08) {
        $("#clearall").click();
    } else if (keycode === 46 || keycode === 44) {
        $("#decimal").click();
    }  
});

You can find the complete project on JSFiddle: http://jsfiddle.net/depauw/XfRDx/ I don't think that the 'clearall' function is broken. 您可以在JSFiddle上找到完整的项目: http : //jsfiddle.net/depauw/XfRDx/我不认为'clearall'函数已损坏。 when i push the button on the screen, the clear all function is executed. 当我按屏幕上的按钮时,将执行清除所有功能。

What i want to achieve is: when a user made a mistake inputting his/her number, he/she can delete it by pressing the delete button and/or the backspace button. 我要实现的是:当用户输入错误的号码时,他/她可以通过按Delete键和/或Backspace键将其删除。

I already tried replacing 'keypress' by keydown of keyup, but that disabled the keyboard input. 我已经尝试用keyup的keydown代替'keypress',但是禁用了键盘输入。 That was probably a stupid mistake, but i'm a real beginner, learning with tutorials, sample codes, and bits of code from everywhere! 那可能是一个愚蠢的错误,但是我是一个真正的初学者,从世界各地学习教程,示例代码和部分代码!

Kind regards for your help!!!, Christophe 谢谢您的帮助!,克里斯托夫

The problem is due to keypress function. 问题归结于按键功能。 Use keyup function instead keypress. 使用按键功能代替按键。 keyup has more capability to handle native keys. keyup具有更多处理本机密钥的功能。 See jquery documentation. 请参阅jquery文档。

    $(document).keyup(function(event){  /*your stuff is here */   });

Checkout a good explanation of difference between these jquery events 检出这些jquery事件之间差异的很好解释

http://howtodoinjava.com/2013/12/20/jquery-keyup-function-demo/ http://howtodoinjava.com/2013/12/20/jquery-keyup-function-demo/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM