如何用JavaScript获取text类型input值,实现设备输入输出类型判断
问题分析与修复方案
你的代码核心问题在于页面加载时就提前获取了输入框的值,此时用户还没输入任何内容,变量x会一直是空字符串,导致点击按钮时的判断完全失效。
快速修复版本
直接将获取输入值的逻辑移到按钮的点击事件中,确保每次点击都读取当前输入框的最新内容:
<h1>Input or output device?</h1> device name: <input type="text" id="device"> <br><br> <button onclick='const x = document.getElementById("device").value.trim().toLowerCase(); alert(x === "mouse" ? "input device":"output device")'>Check now</button>
- 新增
trim()去除输入内容的首尾空格,避免误判 - 新增
toLowerCase()兼容大小写输入(比如输入Mouse也能正确识别)
更规范的可扩展版本
将JS逻辑与HTML结构分离,便于后续维护和扩展更多设备类型:
<h1>Input or output device?</h1> device name: <input type="text" id="device"> <br><br> <button id="checkBtn">Check now</button> <script> document.getElementById("checkBtn").addEventListener("click", function() { const deviceValue = document.getElementById("device").value.trim().toLowerCase(); // 可根据需求添加更多设备类型 const isInputDevice = ["mouse", "keyboard", "scanner", "microphone"].includes(deviceValue); const isOutputDevice = ["monitor", "speaker", "printer", "headphones"].includes(deviceValue); const deviceType = isInputDevice ? "input device" : isOutputDevice ? "output device" : "unknown device"; alert(deviceType); }); </script>
这种写法不仅结构清晰,还能轻松添加更多设备的判断逻辑,提升代码的可维护性。
内容的提问来源于stack exchange,提问作者Athier Hamad
相关产品推荐
相关产品推荐

