我正在创建一个纸牌游戏,其中用户将选择 3 张纸牌,然后将选择的纸牌添加到名为“chosenCards”的数组中。然后,我根据卡片的索引号将卡片打印到新的 DIV 中。我希望能够基本上说“如果 selectedCard[0] 的 div 类为 'card1',则将“一些文本”打印到 DIV。
我尝试以各种方式完成此任务,但无法弄清楚如何比较数组中的 div 或使用 switch case 的方法。
我最终尝试将卡添加到 div 中,然后检查 div 中是否包含卡的类以及它是否打印出“一些文本”,但这不起作用,因为它给了我一个错误“cannot”读取 null 的属性“classList””。
编辑/更新:
我更改了代码以通过执行以下操作来搜索子元素:
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"))
。
关于javascript - 尝试将文本附加到 Else If 中的 DIV 时,无法读取 Null 的 "classList"属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57661017/