javascript - 尝试在 Else If 中将文本附加到 DIV 时无法读取 Null 的“classList”属性
问题描述
我正在创建一个纸牌游戏,用户将在其中选择 3 张牌,然后将挑选的牌添加到名为“chosenCards”的数组中。然后我根据它们的索引号将卡片打印到一个新的 DIV 中。我希望能够基本上说“如果 selectedCard[0] 的 div 类为 'card1',则将“一些文本”打印到 DIV。
我试图以各种方式完成此操作,但无法弄清楚如何比较数组中的 div 或使用 switch 案例的方法。
我最终尝试将卡片添加到 div 然后检查 div 中是否包含卡片的类 & 如果它确实打印出“一些文本”但那不起作用,因为它给了我一个错误“无法读取属性” classList' 为 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";
}
我希望结果看起来像这样:
结果
你对自己的感觉如何:
[隐士卡]:“一些文字”
解决方案
classList 是附加到元素的类列表,因此如果您有#cardResults.card1
. 相反,您想if(document.querySelector("#cardResults .card1"))
在子元素中搜索类时使用。
推荐阅读
- ruby-on-rails - Ruby Rails:保存 JSON 并将其解析回视图中的布尔值
- php - 如何更改模态窗口的标题?
- c# - Web API 设计问题 - 阻止用户使用 PUT/PATCH 更新用户 ID
- excel - VBA cells.find返回值而不是地址
- java - Java中finalize方法的问题
- azure - 如何监视 Azure Functions 异常
- excel - 根据事先未知的值为单元格标题着色
- c++ - 使用 Monte Carlo Alogrithim 计算热平衡分布的程序中 C++ 似乎跳过行的问题
- xcode - 在多台计算机上处理 Xcode 项目
- python - 将带有字母的字母数字电话号码转换为数字