Javascript 使用 jQuery 识别退格和空格键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8222809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:10:46  来源:igfitidea点击:

Recognize the backspace and spacebar with jQuery

javascriptjquery

提问by Michael Rader

when a user clicks the spacebar or backspace I need to create a variable that stores the action so I can use it to manipulate an array. I want the backspace to delete a value in an array and the spacebar to create a space. How can I do this?

当用户单击空格键或退格键时,我需要创建一个存储操作的变量,以便我可以使用它来操作数组。我希望退格键删除数组中的值,空格键创建一个空格。我怎样才能做到这一点?

回答by Saeed Neamati

Maybe this can help you:

也许这可以帮助你:

$('body').keyup(function(e){
   if(e.keyCode == 8){
       // user has pressed backspace
       array.pop();
   }
   if(e.keyCode == 32){
       // user has pressed space
       array.push('');
   }
});

回答by run

try this

尝试这个

$(document).ready( function() {
        $('#inputid').bind('keypress', function(e) {
            if (e.which == 32){//space bar
                alert('space');
            }
            if (e.which == 8) {//backspace
                alert('back space');
            }
    });


    });

回答by Irvin Dominin

Try this fiddle: http://jsfiddle.net/gSWwp/1/

试试这个小提琴:http: //jsfiddle.net/gSWwp/1/

I call the method e.preventDefault(); for ignore the default event associated to the keypress for a field. http://api.jquery.com/event.preventDefault/

我调用方法 e.preventDefault(); 忽略与字段按键相关的默认事件。 http://api.jquery.com/event.preventDefault/

回答by Safeer Ahmed

It scrolled down the page!I wanted to use the space bar key to trigger a function as:

它向下滚动页面!我想使用空格键来触发一个函数:

$("#org").on("keydown", function(e){
        if(e.keyCode == 32){
            my_func();//The function executes but the page is scrolled down
        }
});

Now I have changed the code and added return falseand it worked perfectly as I don't want space in typed word as well.

现在我已经更改了代码并添加了return false并且它工作得很好,因为我也不希望输入的单词中有空格。

$("#org").on("keydown", function(e){
        if(e.keyCode == 32){
            my_func();
            return false;//to fix the scrolling down on space bar key press
        }
});