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

JavaScript中两个变量对比始终判定为不相等的问题如何解决

问题原因

document.getElementById("word") 获取的是页面对应id的DOM元素对象,不是用户输入的文本值。你直接用DOM对象和字符串"word"做全等比较,结果永远不相等,所以每次都会触发错误提示。

修复方案

获取元素后追加.value属性,就能拿到输入框内的用户输入文本,修正后的代码如下:

function wordcompare() {
  var word1 = "word";
  var typed = document.getElementById("word").value;

  if (typed === word1) {
    alert("Correct word");
  } else {
    alert("Incorrect word");
  }
}

可选优化

如果要规避用户误输入首尾空格的问题,可以给获取到的内容加个去空格处理:

var typed = document.getElementById("word").value.trim();

内容的提问来源于stack exchange,提问作者Gerard Du Pre

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:39:03