首页 > 解决方案 > 如何在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;
};

标签: javascripthtml

解决方案


是的,您可以通过创建事件处理程序并在两种情况下都使用该事件处理程序来减小大小,

<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;

推荐阅读