尝试在单击div时找到显示console.log的方法.我正在尝试做一个简单的游戏,如果你点击右边的框,你会收到一条你赢了的消息.
截至目前,我正在努力解决我的代码问题,特别是这一部分:
function winningBox(){
if (boxes.hasClass){
console.log('you win');
} else {
console.log('you lose');
}
}
winningBox();Run Code Online (Sandbox Code Playgroud)
我如何让它工作?如果点击的框具有"获胜"类,则该消息应该是console.log获胜.请看一下.顺便说一下,我需要在Vanilla 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
}Run Code Online (Sandbox Code Playgroud)
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;
}Run Code Online (Sandbox Code Playgroud)
<body>
<container class="main">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</container>
<script src="main.js"></script>
</body>Run Code Online (Sandbox Code Playgroud)
您可以使用Element.classList.contains函数来检查元素的class属性中是否存在指定的类值.
所以断言应该是这样的:
if (boxes.classList.contains('winning')) {
Run Code Online (Sandbox Code Playgroud)
UPD
正如Karl Wilbur在评论中注意到的那样,boxes是一个NodeList实例.
所以,你必须将它转换为数组:
var boxes = Array.prototype.slice.apply(document.getElementsByTagName('li'));
Run Code Online (Sandbox Code Playgroud)
你将能够迭代它:
boxes.some(function(el) {
return el.classList.contains('winning');
});
Run Code Online (Sandbox Code Playgroud)
如果至少有一个框包含类名"wins",则应该返回true.
| 归档时间: |
|
| 查看次数: |
22147 次 |
| 最近记录: |