Javascript 使用 jQuery 防止在 HTML 文本框中键入空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11268222/
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
Prevent typing spaces in an HTML text box with jQuery
提问by alt
So I've got an HTMLform that users can type in. How can I use javascript/jQuery to immediately and seamlessly remove spaces from a text box when one is put in? I've been researching the .val()jQuery method and came up with this:
所以我有一个HTML用户可以输入的表单。我如何使用 javascript/jQuery 在文本框中立即无缝地从文本框中删除空格?我一直在研究.val()jQuery 方法并想出了这个:
$('input').keydown(function() {
str = $(this).val();
str = str.replace(/\s/g,'');
$(this).val(str);
});
That does weird things to removing text and the spaces still show up on keystroke, they just get removed on the following keystroke. Any suggestions?
这对删除文本做了奇怪的事情,并且空格仍然出现在击键时,它们只是在接下来的击键中被删除。有什么建议?
回答by James Allardice
You could prevent it from being added at all by checking whether the key pressed is the space bar and returning falseif so:
您可以通过检查按下的键是否为空格键并返回(false如果是)来阻止它被添加:
?$("input").on("keydown", function (e) {
return e.which !== 32;
});?????
Here's a working example.
这是一个工作示例。

