如何基于数值输入框值显示/隐藏单选输入框(仅用JavaScript)
表单控件显示逻辑报错排查与修复
问题背景
我有一个表单,包含两个数值输入框(betsHome和betsAway)以及两个单选输入框(widgetHome和widgetAway)。单选输入框默认隐藏,我希望仅用JavaScript实现:当两个数值输入框值相同时,显示单选输入框。
我写了如下脚本,但控制台一直报错:TypeError: undefined is not an object (evaluating 'other.value'),脚本无法正常运行:
betHome.addEventListener('input', function (ev) { hideOrShowWidget(ev, betAway, widgetHome, widgetAway) }); betAway.addEventListener('input', function (ev) { hideOrShowWidget(ev, betHome, widgetHome, widgetAway) }); function hideOrShowWidget(event, other, widgetHome, widgetAway) { if (event.value === other.value) { widgetHome.style.visibility = 'visible'; widgetAway.style.visibility = 'visible'; } else { widgetHome.style.visibility = 'hidden'; widgetAway.style.visibility = 'hidden'; } }
错误原因拆解
这个报错主要有两个关键问题:
1. 事件对象没有value属性
你在hideOrShowWidget里直接用了event.value,但input事件的事件对象本身并不携带value属性——输入框的value应该从事件的触发目标,也就是event.target上获取,它才是当前输入的那个DOM元素。
2. DOM元素可能未正确获取
如果betHome、betAway这些变量没有通过document.getElementById或其他方法正确指向页面上的DOM元素,那么传入hideOrShowWidget的other参数就会是undefined,访问other.value自然会报错。
修正后的完整代码
先确保正确获取DOM元素,再修复事件对象的value获取方式,修正后的代码如下:
// 第一步:先获取页面上的DOM元素(替换成你实际的id选择器) const betHome = document.getElementById('betsHome'); const betAway = document.getElementById('betsAway'); const widgetHome = document.getElementById('widgetHome'); const widgetAway = document.getElementById('widgetAway'); // 绑定输入事件监听器 betHome.addEventListener('input', function (ev) { hideOrShowWidget(ev, betAway, widgetHome, widgetAway) }); betAway.addEventListener('input', function (ev) { hideOrShowWidget(ev, betHome, widgetHome, widgetAway) }); // 修复后的核心逻辑函数 function hideOrShowWidget(event, other, widgetHome, widgetAway) { // 从事件目标元素获取当前输入值 const currentValue = event.target.value; // 注意:数值输入框的value是字符串类型,若需要严格数值比较,要转成Number if (currentValue === other.value) { widgetHome.style.visibility = 'visible'; widgetAway.style.visibility = 'visible'; } else { widgetHome.style.visibility = 'hidden'; widgetAway.style.visibility = 'hidden'; } }
额外优化建议
- 数值类型比较:如果你的输入框是
type="number",但value返回的仍是字符串,若要避免"5"和5不相等的情况,可以转成数字再比较:if (Number(currentValue) === Number(other.value)) { // 执行显示逻辑 } - 初始化检查:页面加载完成后,建议主动检查一次输入框的值,确保单选框的初始状态符合预期:
window.addEventListener('load', function() { // 模拟一个事件对象传入,初始化检查状态 hideOrShowWidget({ target: betHome }, betAway, widgetHome, widgetAway); });
内容的提问来源于stack exchange,提问作者clangroth
相关产品推荐
相关产品推荐

