javascript - 如何在javascript中选择两个带有id的元素?
问题描述
无论如何合并javascript的元素以减少代码大小?
<form>
<input id="input1" type="text"/>
<input id="input2" type="text"/>
</form>
//javascrypt
document.getElementById("input1").onkeypress = function(e) {
var chr = String.fromCharCode(e.which);
if ("1234567890qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM".indexOf(chr) < 0) return false;
};
document.getElementById("input2").onkeypress = function(e) {
var chr = String.fromCharCode(e.which);
if ("1234567890qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM".indexOf(chr) < 0) return false;
};
解决方案
是的,您可以通过创建事件处理程序并在两种情况下都使用该事件处理程序来减小大小,
<form>
<input id="input1" type="text"/>
<input id="input2" type="text"/>
</form>
//javascrypt
const keyPressHandler = (e) => {
var chr = String.fromCharCode(e.which);
if ("1234567890qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM".indexOf(chr) < 0) return false;
};
document.getElementById("input1").onkeypress = keyPressHandler;
document.getElementById("input2").onkeypress = keyPressHandler;
推荐阅读
- mongodb - 使用 MongoDB Spring Data Aggregation 匹配日期时间字段的问题
- c# - 将标签定位到对象
- jquery - 将更改事件jQuery上的字符串“.00”(零零点)连接到输入
- java - 无法在 Java 中的 Actionlistener 中停止计时器重复
- angular - 如何在Angular 9中按回车键触发按钮
- php - laravel 的 rest api 中驱动程序的响应
- python - 使用正则表达式模式重建字符串并捕获组
- javascript - 如何在切换一个类后删除它
- python - 预期的设备 cuda:0 但在我已经将设备分配为 cuda 时在 PyTorch 中获得了设备 cpu
- java - Wicket:手动设置 DateTextField 的值