尝试寻找一种方法,在点击一个 div 元素时显示 console.log。我正在尝试制作一个简单的游戏,如果你点击正确的方框,你将收到一条消息,告诉你赢了。
目前,我在我的代码底部遇到了困难,尤其是这部分:
目前,我在我的代码底部遇到了困难,尤其是这部分:
function winningBox(){
if (boxes.hasClass){
console.log('you win');
} else {
console.log('you lose');
}
}
winningBox();
我该如何让它工作?如果被点击的方框有'winning'类,那么消息应该在控制台中打印出'winning'。请看一下代码。顺便说一句,我需要用原生JavaScript完成这个任务。
//cup game
//add three cups to screen
//select li element
var button;
var boxes = document.getElementsByTagName('li');
var array = [];
console.log('working');
document.addEventListener('DOMContentLoaded', init);
function init() {
document.addEventListener('click', winningBox);
//shuffle li elements, and ad an id
function test(boxes) {
var randomBox = boxes[Math.floor(Math.random() * boxes.length)];
array.push(randomBox);
console.log('randombox:', randomBox);
randomBox.classList.add('winning');
}
console.log(test(boxes));
//user can click on a cup to see if correct
function winningBox() {
if (boxes.hasClass) {
console.log('you win');
} else {
console.log('you lose');
}
}
winningBox();
//if cup is incorrect, display message
//if correct, display won message
//button to restart game
}
body {
background-color: #bdc3c7;
}
.main {
background-color: #2c3e50;
width: 300px;
height: 100px;
}
li {
background-color: gray;
width: 80px;
height: 80px;
margin: 10px;
list-style-type: none;
display: inline-block;
position: relative;
}
<body>
<container class="main">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</container>
<script src="main.js"></script>
</body>
boxes.classList
是undefined
,那么你可能将boxes
视为元素数组。你可能需要迭代boxes
。 - Karl WilburclassList.contains('class_name')
对我有用 :) - Omer