为什么keyup有时会被解雇两次?
我随后使用了unbind和bind,但似乎不起作用。
我的代码HTML
<div id="otpmsg" class="error-otp text-center"></div>
<div id="otp" name="otp" class="form-group text-center">
<input class="m-2 text-center otp-control otp-control-solid" type="text" id="first" maxlength="1" />
<input class="m-2 text-center otp-control otp-control-solid" type="text" id="second" maxlength="1" />
<input class="m-2 text-center otp-control otp-control-solid" type="text" id="third" maxlength="1" />
<input class="m-2 text-center otp-control otp-control-solid" type="text" id="fourth" maxlength="1" />
</div>Javascript部分:
$('#otp').unbind('keyup');
$('#otp').bind('keyup', function (e) {
e.preventDefault();
const inputs = document.querySelectorAll('#otp > *[id]');
let compiledOtp = '';
for (let i = 0; i < inputs.length; i++) {
compiledOtp += inputs[i].value;
}
otp = compiledOtp;
if(otp.length == 4) {
....发布于 2021-01-25 06:03:27
当释放密钥时将触发keyup事件。当使用密钥组合(例如Shift + Tab)时,将根据所使用的键组合触发事件两次或两次以上。
keyup事件将为组合键Shift + Tab触发两次。一个事件用于Shift,一个事件用于Tab。
您可以通过在回调函数中写入一个条件来处理这种情况,通过使用event.key属性获取用户按下的键的值,只允许数字(考虑到OTP将是数字)。
$("#otp").on("keyup", function (e) {
e.preventDefault();
const pressedKey = e.key;
if (!/^[0-9]+$/.test(pressedKey)) {
return;
}
const inputs = document.querySelectorAll("#otp > *[id]");
let compiledOtp = "";
for (let i = 0; i < inputs.length; i++) {
compiledOtp += inputs[i].value;
}
otp = compiledOtp;
if (otp.length == 4) {
...
});有关更多信息,请参阅文档https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
发布于 2021-01-25 03:37:12
我把延迟(500毫秒)加在键盘上,但看起来很有效。但我不知道,这是避免我的问题的正确方法吗?
发布于 2021-01-25 03:40:38
.bind()被否决了。试着使用.on(),看看这是否有帮助?
有关更多信息,请参见https://api.jquery.com/bind/
编辑:对于.unbind()也一样,使用.off()代替。这可能对问题没有帮助,但希望这就是原因。
https://stackoverflow.com/questions/65878424
复制相似问题