gpt4 book ai didi

javascript - 如何限制在 JQuery 中从由不带空格的字母组成的输入字段中获取输入

转载 作者:太空宇宙 更新时间:2023-11-04 16:20:50 24 4
gpt4 key购买 nike

我想从文本字段获取输入,值应该由字母组成,并且之间不应该有任何空格?请让我知道如何实现这一目标?代码如下;

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

最佳答案

了解正则表达式。它们很有趣,您可以在这里测试它们:https://regex101.com/

在替换中使用正则表达式来查找所有非字母字符:

// no-conflict-safe document ready
jQuery(function($) {
// bind using on to a *class* instead of an id.
$(".numbers-only").on("keyup blur", function() {
// use a regex that finds all non-alpha characters
$(this).val($(this).val().replace(/[^a-z]/ig, ''));
});
});

工作 fiddle :https://jsfiddle.net/cale_b/602wuwmx/

改进代码的注意事项:
1.使用on而不是bind 。 (根据 bind 文档,自 jQuery 1.7 起,bind 已被 .on() 方法取代,用于将事件处理程序附加到文档,因此已不鼓励使用它。)< br/>2. 绑定(bind)到class而不是id。通过这种方式,您可以使多个输入以这种方式运行。

关于javascript - 如何限制在 JQuery 中从由不带空格的字母组成的输入字段中获取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40659581/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com