Javascript 如何使用jQuery防止空格键进入空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3859170/
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-23 06:23:10  来源:igfitidea点击:

How to use jQuery to prevent the space key from entering a space?

javascriptjquery

提问by quakkels

I thought it would be a simple thing to hiHyman the space key when in a form input so that it would function like a hyphen. Generally jQuery makes stuff like this really simple.

我认为在表单输入中劫持空格键是一件简单的事情,以便它像连字符一样起作用。一般来说,jQuery 使这样的事情变得非常简单。

The code I tried is this:

我试过的代码是这样的:

        $("#StreamUrl").keydown(function (e) {
            if (e.keyCode == 32) return 109;
        });

But this has no effect whatsoever. I tried a more simple script:

但这没有任何影响。我尝试了一个更简单的脚本:

        $("#StreamUrl").keydown(function (e) {
            //if (e.keyCode == 32) return 109;
            alert(e.keyCode);
        });

This script correctly alerts 32 on space press and 109 on hyphen press. Also, I have no JavaScript errors.

此脚本在按空格键时正确提示 32,在按连字符时提示 109。另外,我没有 JavaScript 错误。

Why wouldn't if (e.keyCode == 32) return 109;work? When I replace that line with if (e.keyCode == 32) alert("space!!");I get the alert correctly, so I know the ifis returning truecorrectly.

为什么if (e.keyCode == 32) return 109;不起作用?当我用if (e.keyCode == 32) alert("space!!");我正确地收到警报替换该行时,所以我知道if正在true正确返回。

What gives?

是什么赋予了?

Edit - Solution

编辑 - 解决方案

Thanks to @Nick for pointing out the copy-paste issue. I ended up with a little bit of a hybrid. Here's the code that I have gotten to work which is both smooth and handles Copy/Paste.

感谢@Nick 指出复制粘贴问题。我最终得到了一点混合动力。这是我开始工作的代码,它既流畅又处理复制/粘贴。

        $("#StreamUrl").keydown(function (e) {
            if (e.keyCode == 32) {
                $(this).val($(this).val() + "-"); // append '-' to input
                return false; // return false to prevent space from being added
            }
        }).change(function (e) {
            $(this).val(function (i, v) { return v.replace(/ /g, "-"); }); 
        });

回答by Cristian Sanchez

The problem is that return 109doesn't do what you want it to do. In an event handler, you return true or false depending on whether or not you want the browser to execute the default action. In keydown, you would return false to prevent the character from being inserted.

问题是return 109它没有做你想让它做的事情。在事件处理程序中,返回 true 或 false 取决于您是否希望浏览器执行默认操作。在 中keydown,您将返回 false 以防止插入字符。

$("#StreamUrl").keydown(function (e) {
     if (e.keyCode == 32) { 
       $(this).val($(this).val() + "-"); // append '-' to input
       return false; // return false to prevent space from being added
     }
});

jsfiddle example

jsfiddle 示例

回答by Nick Craver

You usuallywant the keyupevent instead here, which fires afterthe space has been added, something like this is a bit easier:

通常希望keyup事件发生在这里,在添加空间触发,这样的事情更容易一些:

$("#StreamUrl").bind("keyup change", function () {
  $(this).val(function(i, v) { return v.replace(/ /g,"-"); });
});

Try it out here, what this does is allow the space to be added, but then instantly does a replace of spaces for hyphens by passing a function to .val(). For older versions of jQuery, it'd look like this:

在这里尝试一下,这样做是允许添加空格,然后立即通过将函数传递给.val(). 对于旧版本的 jQuery,它看起来像这样:

$("#StreamUrl").bind("keyup change", function () {
  $(this).val($(this).val().replace(/ /g,"-"));
});

This works even for people pasting content, an easy way to get around keydownvalidation.

这甚至适用于粘贴内容的人,这是一种绕过keydown验证的简单方法。