【发布时间】:2020-01-14 15:41:33
【问题描述】:
我正在尝试检测 input 字段上的后退按钮按下。我试过e.key 和e.which,在移动Chrome 中是undefined。我怎样才能让它工作?在桌面上它工作正常。
jQuery(function($) { // DOM ready and $ alias secured
let aadhaar = "";
let aadhaarStack = [];
let maskStack = [];
let flag = 0;
$('#aadhaar').on('input', function(e) {
let key = e.which || this.value.substr(-1).charCodeAt(0);
console.log("here also")
if (flag === 1) {
console.log("here")
aadhaarStack.pop();
maskStack.pop();
} else {
key = String.fromCharCode(key);
if (aadhaarStack.filter(i => i !== " ").length <= 11 && !isNaN(key)) {
if (aadhaarStack.length > 1 && (aadhaarStack.filter(i => i !== " ").length) % 4 === 0) {
aadhaarStack.push(" ");
aadhaarStack.push(key);
maskStack.push(" ");
if (aadhaarStack.filter(i => i !== " ").length > 8) {
maskStack.push(key);
} else {
maskStack.push("X");
}
} else {
aadhaarStack.push(key);
if (aadhaarStack.filter(i => i !== " ").length > 8) {
maskStack.push(key);
} else {
maskStack.push("X");
}
}
}
}
updateUi();
});
function updateUi() {
setTimeout(function() {
aadhaar = maskStack.join("");
$('#aadhaar').val(aadhaar);
}, 100);
}
$('#aadhaar').on('keydown', function(e) {
alert(e.key);
let key = e.which || this.value.substr(-1).charCodeAt(0);
if (key === 8 || key === 46 || e.key === 'Backspace') {
flag = 1;
} else {
flag = 0;
}
console.log("first here")
})
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<input type="text" maxliength="14" id="aadhaar" autocomplete="off" />
这里是 JSBin 链接https://jsbin.com/rogepevutu/1/edit?html,js,console,output
【问题讨论】:
-
从代码的行为看来,您只是想用
X字符隐藏用户输入。因此,为什么不直接使用type="password"输入...? -
还要注意
maxliength需要改成maxlength -
@RoryMcCrossan 它不仅会更改字符,还会在每四个字符后添加空格,最后 4 个字符也应该可见
标签: javascript jquery