网格(如果框具有特定的类停止JavaScript)

时间:2019-02-25 08:43:08

标签: javascript jquery css

我有一个带有播放器,黄色框,障碍物(.ob)和黑色框的网格。当我单击“向上”按钮时,我不希望玩家进入障碍物方块。

我当时正在考虑检查下一堂课是否有.ob,不要去那里。有什么建议吗?

let moveCounter = 0;
var grid = document.getElementById("grid-box");

for (var i = 1; i <= 50; i++) {
  var square = document.createElement("div");
  square.className = 'square';
  square.id = 'square' + i;
  grid.appendChild(square);
}

var obstacles = [];

while (obstacles.length < 20) {
  var randomIndex = parseInt(49 * Math.random());
  if (obstacles.indexOf(randomIndex) === -1) {
    obstacles.push(randomIndex);

    var drawObstacle = document.getElementById('square' + randomIndex);
    $(drawObstacle).addClass("ob")
  }
}
var playerTwo = [];

while (playerTwo.length < 1) {
  var randomIndex = parseInt(49 * Math.random());

  if (playerTwo.indexOf(randomIndex) === -1) {
    playerTwo.push(randomIndex);

    var drawPtwo = document.getElementById('square' + randomIndex);
    $(drawPtwo).addClass("p-1")
  }
};

$('#button_up').on('click', function() {
  moveCounter += 1;

  $pOne = $('.p-1')
  var id = $pOne.attr('id')
  var idNumber = +id.slice(6);
  var idMove = idNumber - 10
  var idUpMove = 'square' + idMove;
  $pOne.removeClass('p-1');
  $('#' + idUpMove).addClass('p-1');
});
#grid-box {
  width: 400px;
  height: 400px;
  margin: 0 auto;
  font-size: 0;
  position: relative;
}

#grid-box > div.square {
  font-size: 1rem;
  vertical-align: top;
  display: inline-block;
  width: 10%;
  height: 10%;
  box-sizing: border-box;
  border: 1px solid #000;
}

.p-1 {
  background-color: yellow;
}

.ob {
  background-color: black;
}
<div id="grid-box"></div>
<div class="move">
  <button id="button_up">UP</button><br>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

jsFifddle

1 个答案:

答案 0 :(得分:1)

使用以下代码

$('#button_up').on('click', function() {
  moveCounter += 1;

  $pOne = $('.p-1')
  var id = $pOne.attr('id')
  var idNumber = +id.slice(6);
  var idMove = idNumber - 10
  var idUpMove = 'square' + idMove;
  if($('#' + idUpMove).hasClass('ob')){
      return false;
  }
  $pOne.removeClass('p-1');
  $('#' + idUpMove).addClass('p-1');
});

在这里,我们检查下一个选定的具有“ .ob”类的类,如果它返回true,则停止该过程,如果它返回false,则继续进行

if($('#' + idUpMove).hasClass('ob')){
      return false;
  }

Fiddle