【发布时间】: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