Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/439.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript中启用箭头键_Javascript_Jquery - Fatal编程技术网

如何在javascript中启用箭头键

如何在javascript中启用箭头键,javascript,jquery,Javascript,Jquery,在我的应用程序中,我为一个文本字段(用户名)编写了java脚本验证。因此,它只允许字母、空格、空格和箭头在文本字段中移动上一个和下一个字母。我的代码在mozila firefox中运行良好,但在chrome和IE中不允许使用箭头键 我的代码是这样的 <input class="form-control input-lg" onkeypress="return isCharacterKey(event)" onkeyup="capitalize(this)" id="firstNameSpa

在我的应用程序中,我为一个文本字段(用户名)编写了java脚本验证。因此,它只允许字母、空格、空格和箭头在文本字段中移动上一个和下一个字母。我的代码在mozila firefox中运行良好,但在chrome和IE中不允许使用箭头键

我的代码是这样的

<input class="form-control input-lg" onkeypress="return isCharacterKey(event)" onkeyup="capitalize(this)" id="firstNameSpaceCapital"/>

//此函数允许空格、退格、字母和箭头键
函数isCharacterKey(evt){
var charCode=(evt.which)?evt.which:evt.keyCode;
如果(charCode==32 | | charCode==8 | |(charCode>=37&&charCode=65&&charCode=97&&charCode
事件
未定义,请改用

return isCharacterKey(this)

我认为捕捉键盘事件是个坏主意。因为用户可以使用鼠标粘贴一些文本。因此,我建议使用
oninput
event

我会这样处理您的问题:

注意,对于大写字母,只需要css(至少对于您介绍的案例)

html js
$('firstNameSpaceCapital')。在('keypress',isCharacterKey)上;
函数isCharacterKey(evt){
var charCode=(evt.which)?evt.which:evt.keyCode;

如果(charCode==32 | | charCode==8 | | |(charCode>=37&&charCode=65&&charCode=97&&charCode=97&&charCode为什么要在html元素上附加事件而不是使用已有的jquery绑定?在*
属性上使用
是一种不好的做法。使用
addEventListener
event.preventDefault()
相反。正如@webkit所提到的,使用jQuery来执行此操作。
$(“#firstNameSpaceCapital”).on('keypress'
尝试使用
.bind(
而不是
).on(
我使用了.bind(但没有使用)。我认为isCharacterKey(evt)方法在chrome中工作不正常。如果我这样做了,它会显示错误“意外标记此”。上面的代码在mozila中运行良好,但在chrome和IE中不允许使用箭头键。javascript中是否存在浏览器兼容性?我不这么认为。它不允许使用数字和其他特殊符号,但输入值未定义,因此无法验证任何内容。请检查控制台。
return isCharacterKey(event)
return isCharacterKey(this)
<input class="form-control input-lg" id="firstNameSpaceCapital" />
.input-lg {text-transform:capitalize;}
$('#firstNameSpaceCapital').on('keypress', isCharacterKey);

function isCharacterKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode == 32 || charCode == 8 || (charCode >= 37 && charCode <= 40) || (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)) {
        return true;
    }
    evt.preventDefault();
}