0

无论如何合并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;
};
4

1 回答 1

2

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

<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;
于 2020-12-17T12:35:52.273 回答