通过浏览 stackoverflow,我设法在我的 <input>
上编写了这段代码
onkeyup="this.value = this.value.replace(/[qwertyuopasdfghjklzxcvbnm ]/g, '')"
我打算限制键盘,但字母i、-和数字0-9除外。它对我的程序运行良好,但是有没有更简洁的方法来编写此代码?
最佳答案
由于您只有几个要包含的字符,因此您可以使用负字符集来指定这些字符,而不是指定要删除的字符集:
this.value = this.value.replace(/[^i0-9-]/g, '')
如果可能的话,您还应该考虑使用 Javascript 正确附加事件监听器,而不是使用内联处理程序:
const input = document.querySelector(<input selector>);
input.addEventListener('keyup', function() {
this.value = this.value.replace(/[^i0-9-]/g, '');
});
另一个可能的改进是在 keypress
事件上使用 preventDefault
来代替,而不是让不需要的字符出现一秒钟然后立即消失:
const input = document.querySelector('input');
input.addEventListener('keypress', function(e) {
if (!/[i0-9-]/.test(e.key)) {
e.preventDefault();
}
});
<input>
(不过,上面仍然允许通过粘贴和单击拖动等方式输入这些字符,因此当这些事件被触发时,您将不得不求助于 .replace
方法)
关于javascript - 编写此代码的更简洁方法[限制 <input> 上的字符],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54120856/