我在jQuery中从用户输入创建了一个网格(div),如何重置并重新开始



我现在正在学习JS和JQuery,我正在制作一个绘图游戏,现在我需要能够重置游戏。

用户在开始时得到提示并选择网格大小。现在,当我重置时,用户再次被询问,但我找不到正确删除现有单元格的方法。

我想这可能与我如何组织我的功能有关。

任何帮助将是惊人的,我把我的两个选项在那里在脚本的底部。

Thanks in advance

http://codepen.io/Middi/pen/rrgqOv


$(document).ready(function() { 

createGrid();
}); 

function createGrid() {

  // if('.cell'.length > 0) {
  //
  //   $(.cell).remove()
  //
  // }


var boxes = prompt("select a grid between 2 - 128?","0");

var x = parseInt(boxes);
  if(x > 128) {
    alert("must be between 1-128");
  }
    else {

    }
    for(elementCount = 0; elementCount < x; elementCount++) {
      $('#container').append('<div class="col"></div>');

    }
    for(columnCount = 0; columnCount < x; columnCount++) {
      $('.col').append('<div class="cell"></div>');
      $(".cell").width(572/x);
      $(".cell").height(572/x);
    }



    $('.cell').mouseenter(function () {
       $(this).addClass('highlight');
   });

}


function clearButton() {
  $(".cell").removeClass('highlight');
}
// --------- OPTION ONE ---------- //
// function resetButton() {
//   $('#container').remove('.cell');
// }

// --------  OPTION TWO ---------- //
function resetButton() {
  createGrid();
}

尝试删除所有。cell

//like $('#container').empty()
function removeCell() {
   $('#container').empty()
}
function resetButton() {
    removeCell();
    createGrid();
}

你的resetButton只创建新的网格,这意味着它重新定义你现有的网格…如果你想在调整大小之前清除它,你可以在调整大小之前调用clearButton()函数。

function resetButton() {
  clearButton();
  createGrid();
}

我在你的例子中测试了,它做到了!这是你想要的吗?

最新更新