【问题标题】:Cannot read property of "classList" of Null when trying to append text to a DIV in Else If尝试在 Else If 中将文本附加到 DIV 时无法读取 Null 的“classList”属性
【发布时间】:2019-08-28 00:06:52
【问题描述】:

我正在创建一个纸牌游戏,其中用户将选择 3 张纸牌,然后将选择的纸牌添加到名为“chosenCards”的数组中。然后我根据它们的索引号将卡片打印到一个新的 DIV 中。我希望能够基本上说“如果 selectedCard[0] 的 div 类为 'card1',则将“一些文本”打印到 DIV。

我试图以各种方式完成此操作,但无法弄清楚如何比较数组中的 div 或使用 switch 案例的方法。

我最终尝试将卡片添加到 div 中,然后检查 div 中是否包含卡片的类以及是否打印出“一些文本”,但这不起作用,因为它给了我一个错误“不能读取属性 'classList' of null"。

编辑/更新:

我更改了代码以通过以下方式搜索子元素:

if(document.querySelector("#cardResults .card1").classList.contains("card1"))

但是,当我向其添加 else 时,同样的错误再次发生。 这是现在破坏它的代码:

         document.getElementById("re").innerHTML = "The Hermit suggests that you are in a phase of introspection where you are drawing your attention inwards and looking for answers within. You are in need of a period of inner reflection, away from the current demands of your position.";
         }
         else if(document.querySelector("#cardResults .card2").classList.contains("card2")){
           document.getElementById("re").innerHTML = "You are a fool";
         }

         else {
          document.getElementById("re").innerHTML = "error";
         }

我希望结果看起来像这样:

结果

你对自己的感觉:

[隐士卡]:“一些文字”

【问题讨论】:

  • 这是因为cardResults 不是一个类它是一个id。请改用querySelector('#cardResults')
  • @GetOffMyLawn 不错!我只是尝试过,但也没有用..

标签: javascript html if-statement


【解决方案1】:

classList 是附加到元素的类列表,因此如果您有#cardResults.card1,它将起作用。相反,您想在子元素中搜索类时使用if(document.querySelector("#cardResults .card1"))

【讨论】:

  • 没有考虑子元素。谢谢!
  • 由于某种原因,当我将其放入 if else 中时,它不再起作用...
  • @Chris 如果您只是从我的答案中复制,可能是因为我没有关闭括号,编辑了答案
  • 刚刚试了一下,效果很好!谢谢你。我假设它不需要它,因为它已经在 querySelector 中定位?
猜你喜欢
  • 2019-04-10
  • 2019-03-25
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 2021-11-07
  • 2021-11-21
  • 2013-06-22
  • 1970-01-01
相关资源
最近更新 更多