You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 23:21:06