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

JavaScript输入框输入sadra不触发alert且无报错如何解决

存在的问题

  • 输入框内容获取方式错误:<input> 是自闭合标签,用户输入的内容存储在 value 属性中,你使用 innerHTML 只能获取到空字符串,永远无法匹配到关键词,所以不会触发弹窗。
  • 变量逻辑冗余冲突:全局声明的realText、函数入参realText、函数内部重新声明的realText三者命名重复,且传递的参数没有任何实际作用,完全可以去掉。
  • (可选优化)onchange 事件仅在输入框失去焦点时才触发,如果需要输入过程中实时检测关键词,可以替换为 oninput 事件。

修正后代码

JS 代码

function checkText() {
  const realText = document.getElementById('input1').value;
  if (realText.includes('sadra')) {
    alert("your text contains \"sadra\" word ");
  }
}

HTML 代码

<label>Input :</label>
<input type="text" name="test" id="input1" onchange="checkText()" />

内容的提问来源于stack exchange,提问作者IR Fifa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 18:57:00