gpt4 book ai didi

javascript - 小键盘未在 fromCharCode 中给出数字

转载 作者:行者123 更新时间:2023-11-28 19:17:44 24 4
gpt4 key购买 nike

我想只允许在我的输入字段中按下某些按键。

问题是 String.fromCharCode 中的数字键盘值与真实字符不对应...

另外请注意,我的 Chrome 将逗号 (String.fromCharCode(188)) 翻译为“¼” - 尽管它应该是“,”?

我是这样做的:

Javascript指令:

angular.module('LTS').directive('allowed', function () {
return {
restrict: 'A',
link: function (scope, element, attrs, modelCtrl) {
var allowedLowerCaseLetters = attrs.allowed.toLowerCase();
element.on('keydown', function (event) {
var pressedChar = String.fromCharCode(event.keyCode).toLowerCase();
if (event.keyCode === 188) {
pressedChar = ",";
}
if (allowedLowerCaseLetters.indexOf(pressedChar) > -1 || event.keyCode === 8 || event.keyCode === 37 || event.keyCode === 39) {
// console.log(pressedChar+" should be added to model.");
} else {
//TODO maybe add a notification ?
event.preventDefault();
}
});
}
};
});

HTML:

<input id="invoiceAmount" class="form-control importInput" type="text" ng-model="import.invoiceAmount"  allowed="1234567890,">

小心Firefox 的代码位于“event.charCode”中,而不是按键上的 keyCode

最佳答案

String.fromCharCodeevent.keyCode是不同的。

String.fromCharCode 期望 Unicode 代码作为参数,然后返回与其关联的字符。

event.keyCode 在 keydown 事件中实现有点困惑,它们返回被按下的键的代码,而不是打印的字符的代码。但是,在按键事件中使用它将返回预期值以及在 String.fromCharCode 中使用的正确值。

 function f(e){
document.querySelector('div').innerHTML += e.type + ' - ' + e.keyCode + ' - ' + String.fromCharCode(e.keyCode) + '<br/>';
}

document.querySelector('input').addEventListener('keydown', f);
document.querySelector('input').addEventListener('keypress', f);
<input />
<div></div>

关于javascript - 小键盘未在 fromCharCode 中给出数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29492934/

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