【问题标题】:Check if element has class [duplicate]检查元素是否有类[重复]
【发布时间】:2016-06-07 13:04:06
【问题描述】:

试图找到一种在单击 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>

【问题讨论】:

    标签: javascript


    【解决方案1】:

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

    所以断言应该是这样的:

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

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

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

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

    您将能够对其进行迭代:

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

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

    【讨论】:

    • 是的,它给了我某种类型的错误......
    • 那么,如何准确地告诉我们错误信息是什么?
    • 无法读取未定义的“包含”
    • 如果boxes.classListundefined,那么您可能会将boxes 视为一个元素数组。您可能需要迭代 boxes
    • classList.contains('class_name') 为我工作:)
    【解决方案2】:

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

    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

    【讨论】:

      【解决方案3】:

      我认为你想要做的是:

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

      【讨论】:

        猜你喜欢
        • 2017-12-19
        • 2016-05-12
        • 2011-06-15
        • 2012-07-29
        • 2011-06-13
        • 2014-02-17
        • 1970-01-01
        • 2010-11-22
        相关资源
        最近更新 更多