Javascript TypeError 代码错误,变量未定义

Error with Javascript TypeError code, variable undefined

我正在尝试获取 ID 为 1a2a3a 等的元素,根据函数为 运行.

然后将元素值(使用 jQuery)与函数错误的 input 的值进行比较 它提出了一个错误说:

TypeError: var1.toUpperCase is not a function. (in 'var2.toUpperCase()','var1.toUpperCase' is undefined)

如有任何帮助,我们将不胜感激。 谢谢 (UPDATE 通常在 questionNumber 中会有文本,例如:每次另一个函数是 运行 时,1、2、3 等。)


编辑:每次不同的函数是 运行,questionNumber 增加 1。我将 questionNumber 的文本保存在一个名为 word 的变量中。然后我将字母 a 添加到该变量。然后,我获取具有变量 ID word 的元素,然后将其内容与 input 的值进行比较,但比较是大写以避免出现问题。如果它们相等,input 将替换为带有绿色文本的 div。希望这能让它更清楚。

      function textVerify(item) {
          var word= document.getElementById(($('#questionNumber').text()+'a'));
      if (item.value.toUpperCase() === word.toUpperCase()){
          item.style.color = "green";
          $( item ).replaceWith( "<div style='color:green;'>"+word+"</div>" );
          main()
          } else {
              item.style.color = "black";
        }
          <span class="ihide" id="questionNumber"></span>
          <p id="1a" class="ihide">Seven</p>
          <input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">

在您的代码中 ($('#questionNumber').text()+'a') 这部分 returns 只是 'a',因为 id questionNumber 的文本什么都不是。

而您的 HTML 中没有这样的 ID。我认为您需要对 HTML 代码进行此更改:

<span class="ihide" id="questionNumber">1</span>

这应该有效。

编辑:另外,您能否分享与 'item' 关联的 JS 代码,那部分也可能有错误。

var wordp标签,所以你需要获取它的内部文本并与输入文本进行比较。另外,替换它时,访问它的text() 属性。见下文。 main()这里注释掉了,大家可以根据需要保留。

function textVerify(item) {

  var word = document.getElementById(($('#questionNumber').text() + 'a'));

  if (item.value.toUpperCase() === $(word).text().toUpperCase()) {
    item.style.color = "green";
    $(item).replaceWith("<div style='color:green;'>" + $(word).text() + "</div>");
    //main()
  } else {
    item.style.color = "black";
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span class="ihide" id="questionNumber">1</span>
<p id="1a" class="ihide">Seven</p>
<input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">