检查元素是否有类

新手上路,请多包涵

试图找到一种在单击 div 时显示 console.log 的方法。我正在尝试做一个简单的游戏,如果你点击右边的框,你会收到一条你赢了的消息。

截至目前,我正在努力处理代码的底部,尤其是这一部分:

 function winningBox(){

	if (boxes.hasClass){

		console.log('you win');
	} else {
		console.log('you lose');
	}
}
winningBox();

我如何让它工作?如果单击的框具有“winning”类,则消息应该 console.log winning。请看一下。顺便说一句,我需要在 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
}
 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>

原文由 Lucky500 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 325
1 个回答

您可以使用 Element.classList.contains 函数来检查元素的类属性中是否存在指定的类值。

所以断言应该是这样的:

 if (boxes.classList.contains('winning')) {

UPD 正如 Karl Wilbur 在对我的回答的评论中注意到的那样, boxes 是一个 NodeList 实例。

所以,你必须把它转换成数组:

 var boxes = Array.prototype.slice.apply(document.getElementsByTagName('li'));

你将能够迭代它:

 boxes.some(function(el) {
    return el.classList.contains('winning');
});

如果至少有一个框包含类名“winning”,则这应该返回 true。

原文由 Alex Yatkevich 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏