检查元素是否有类

时间:2016-02-25 00:04:01

标签: javascript

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

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

function winningBox(){

	if (boxes.hasClass){

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

我如何让它工作?如果点击的框具有“获胜”类,则该消息应该是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
}
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>

3 个答案:

答案 0 :(得分:7)

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

所以断言应该是这样的:

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');
});

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

答案 1 :(得分:0)

我建议检查每个容器(不是上一个答案中的数组):

function checkawinner(box) {
  box.addEventListener("click", function(){
   if (box.classList.contains('winning')) {
        console.log('you win');
    } else {
        console.log('you lose');
   }
  }, false);
}

for (index = 0; index < boxes.length; ++index) {
  checkawinner(boxes[index]);  
}

带有“提醒”的笔:http://codepen.io/VsevolodTS/pen/BKBjpP

答案 2 :(得分:0)

我认为你要做的是:

//user can click on a cup to see if correct
function winningBox(){
    // ensure that we are not working against a cached list of elements
    var boxes = document.getElementsByTagName('li');
    for(i=0,len=boxes.length;i<len;i++) {
        var box = boxes[i];
        if (box.classList.contains('winning')){
            console.log('you win');
        } else {
            console.log('you lose');
        }
    );
}