如何使用jQuery来防止空格键进入空格? [英] How to use jQuery to prevent the space key from entering a space?

查看:99
本文介绍了如何使用jQuery来防止空格键进入空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我试过的代码就是:

        $("#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);
        });

此脚本在空间按下时正确警告32,在连字符按下时正确警告109。此外,我没有JavaScript错误。

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

为什么不能如果(e.keyCode == 32)返回109; 替换该行时if(e.keyCode == 32)alert(space !!); 我正确地收到警报,所以我知道如果正确返回 true

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 if is returning true correctly.

给出了什么?

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

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.

        $("#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, "-"); }); 
        });


推荐答案

问题是返回109 不能做你想做的事。在事件处理程序中,根据您是否希望浏览器执行默认操作,返回true或false。在 keydown 中,您将返回false以防止插入该字符。

The problem is that return 109 doesn'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.

$("#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示例

这篇关于如何使用jQuery来防止空格键进入空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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