如何用JavaScript通过ID为多个输入框每两位数字间添加空格?
问题原因
你的代码里用document.getElementById("phone") || document.getElementById("secondnumber") || document.getElementById("fax")这种写法,只会拿到第一个匹配的元素(也就是id为phone的输入框),另外两个输入框根本没绑定事件,所以自然不会生效。
两种解决方法
方法一:遍历指定ID列表
把需要处理的输入框ID放进数组,逐个绑定事件:
// 定义数字格式化函数 const formatNumber = (number) => number.split("").reduce((seed, next, index) => { if (index !== 0 && !(index % 2)) seed += " "; return seed + next; }, ""); // 所有要处理的输入框ID const targetInputIds = ["phone", "secondnumber", "fax"]; // 遍历每个ID,绑定输入事件 targetInputIds.forEach(id => { const input = document.getElementById(id); if (input) { input.addEventListener("input", () => { // 先移除所有空格,再执行格式化 input.value = formatNumber(input.value.replaceAll(" ", "")); }); } });
方法二:利用共同类名批量处理
因为三个输入框都有phone类,直接通过类名选中所有目标输入框,更简洁:
const formatNumber = (number) => number.split("").reduce((seed, next, index) => { if (index !== 0 && !(index % 2)) seed += " "; return seed + next; }, ""); // 选中所有class为phone的输入框 const allPhoneInputs = document.querySelectorAll(".phone"); allPhoneInputs.forEach(input => { input.addEventListener("input", () => { input.value = formatNumber(input.value.replaceAll(" ", "")); }); });
额外注意
如果发现type="number"的输入框无法保留空格(部分浏览器会自动过滤非数字字符),可以把输入框的type改成text,同时加上inputmode="numeric"属性,这样既可以正常显示格式化后的空格,又能唤起数字键盘:
<input type="text" inputmode="numeric" class="phone" placeholder="Phone" id="phone" /> <input type="text" inputmode="numeric" class="phone" placeholder="Second Number" id="secondnumber" /> <input type="text" inputmode="numeric" class="phone" placeholder="Fax" id="fax" />
内容的提问来源于stack exchange,提问作者Imy Imy
相关产品推荐
相关产品推荐

