我在那里遇到问题,我一直尝试记录事件键代码,我得到了键号(9)
,我认为我的脚本未禁用event.keyCode
并没有禁用该键功能。我应该对脚本进行哪些更改,以便选项卡可以再次处于活动状态?
这是我的代码:
$(function() {
$('.number-format').on("keydown", function(event) {
console.log(event.keyCode);
if (event.shiftKey) {
event.preventDefault();
}
if (event.keyCode == 46 || event.keyCode == 8) {} else {
if (event.keyCode < 95) {
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
} else {
if (event.keyCode < 96 || event.keyCode > 105) {
event.preventDefault();
}
}
}
});
$('.number-format').on("keyup", function(event) {
var value = this.value.replace(/,/g, "");
this.dataset.currentValue = parseInt(value);
var caret = value.length - 1;
while ((caret - 3) > -1) {
caret -= 3;
value = value.split('');
value.splice(caret + 1, 0, ",");
value = value.join('');
}
this.value = value;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="number-format">
答案 0 :(得分:0)
当选项卡的keyCode为9时,您可以将第二个条件更改为if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9)
并执行else event.preventDefault();
:
$(function() {
$('.number-format').on("keydown", function(event) {
console.log(event.keyCode);
if (event.shiftKey) {
event.preventDefault();
}
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9) {} else {
//------------------------------------------------^^^^^^^^^^^^^^^^^^^^^
//add the tab keyCode in this if to skip it entirely so that it woks again
if (event.keyCode < 95) {
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
//--------^^^^^^^^^^^^^^^^^^^^^^ this is preventing your tab action
}
} else {
if (event.keyCode < 96 || event.keyCode > 105) {
event.preventDefault();
}
}
}
});
$('.number-format').on("keyup", function(event) {
var value = this.value.replace(/,/g, "");
this.dataset.currentValue = parseInt(value);
var caret = value.length - 1;
while ((caret - 3) > -1) {
caret -= 3;
value = value.split('');
value.splice(caret + 1, 0, ",");
value = value.join('');
}
this.value = value;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="number-format">