使用js

时间:2015-12-16 09:27:53

标签: javascript html

首先我有一个表单,有2个文件board字段和myNumb,该表是控制表大小的数字。 myNumb是应随机选择的单元格数。

我试图用javascript选择随机表格单元格。我有一个整数变量myNumb,我将给出应该选择多少随机单元格。在我选择的单元格中,我想放置1,其余的则为0.我已经构建了表格的结构,但是不知道如何选择随机单元格。任何想法都会非常感激。

function tableMatrix () {
    //taking values from the form
    var board = document.forms["myForm"]["board"].value;;
    var myNumb = document.forms["myForm"]["myNumb"].value;
    var zero = 0;
    var one = 1;

    //finding myContainer
    var myContainer = document.getElementById('myContainer');
    myContainer.innerHTML = '';
    //creating element <table>
    var table = document.createElement('table');

    table.style.width = '100%';
    table.setAttribute('border', '1');

    //creating element <tbody>
    var tbody = document.createElement('tbody');

    //cells creation
    for (var i = 0; i < board; i++) {
        //creating <tr> element
        var tr = document.createElement('tr');
        for (var j = 0; j < board; j++) {
            //creating <td> element
            var td = document.createElement('td');
            //put <td> after <tr> element
            tr.appendChild(td);
            td.setAttribute('class', 'tblCells');

            var x = 0;
            if (x <= myNumb) {
                var randomCounter = Math.floor(Math.random() * 9);
                x += randomCounter;
                td.innerHTML = '<span>'+ one +'</span>';
            } else {
                td.innerHTML = '<span>'+ zero +'</span>';
            }
        }
        //put <tr> after <tbody> element
        tbody.appendChild(tr);
    }
    //put <tbody> after <table> element
    table.appendChild(tbody);
    //put <table> after <div> element
    myContainer.appendChild(table);

}

如果有帮助

,我还创建了一个JSFiddle here

3 个答案:

答案 0 :(得分:2)

这是生成所需模式的脚本:

 function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex ;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}
  function fillCells(value, len) {
    var arr = [];
    for (var i = 0; i < len; i++) { if(i<value){
      arr.push(1);}else{arr.push(0);}
    }
    shuffle(arr);
    return arr;
  }

    function tableMatrix () {
  //taking values from the form
    var board = document.forms["myForm"]["board"].value;;
    var myNumb = document.forms["myForm"]["myNumb"].value;
    var zero = 0;
    var one = 1;
    var totalCell = board*board;
   var cellValues =  fillCells(myNumb, totalCell)
//finding myContainer
var myContainer = document.getElementById('myContainer');
    myContainer.innerHTML = '';
//creating element <table>
  var table = document.createElement('table');

  table.style.width = '100%';
  table.setAttribute('border', '1');

  //creating element <tbody>
  var tbody = document.createElement('tbody');

  //generate random number

  var x = 0;
  //cells creation
  for (var i = 0; i < board; i++) {
    //creating <tr> element
      var tr = document.createElement('tr');
      for (var j = 0; j < board; j++) {
        //creating <td> element
            var td = document.createElement('td');
            //put <td> after <tr> element
            tr.appendChild(td);
            td.setAttribute('class', 'tblCells');

            td.innerHTML = '<span>'+cellValues[x]+'</span>';
            x++;

      }
      //put <tr> after <tbody> element
      tbody.appendChild(tr);
  }
  //put <tbody> after <table> element
  table.appendChild(tbody);
  //put <table> after <div> element
  myContainer.appendChild(table);
 } 

这是Bin

答案 1 :(得分:1)

我不确定你选择细胞是什么意思。 您可以在创建表时指定ID,并在以后选择它们:

cell.id = 'cell_' + (rowNum * boardSize + columnNum);

通过这个,您可以选择myNum个单元格并选择它们:

 numberOfCells = boardSize * boardSize;
 // pick a random cell.
 cellId = 'cell_' + Math.floor(Math.random() * numberOfCells);
 document.getElementById(cellId);

我是根据你的小提琴来实现的:

  
function createTable(size) {
  var table, tr, td;
  
  table = document.createElement('table');

  for (var row = 0; row < size; ++row) {
    tr = document.createElement('tr');
    for (var col = 0; col < size; ++col) {
      td = document.createElement('td');
      td.id = 'cell_' + (row * size + col);
      td.innerHTML = '0';
      tr.appendChild(td);
    }
    table.appendChild(tr);
  }
  
  return table;
}

function selectRandomCells(size, count) {
  var x, numCells, cellId, cell;
  
  numCells = size * size;
  x        = 0;
  
  while (x < count && x < numCells) {
    cellId = 'cell_' + Math.floor(Math.random() * numCells);
    cell   = document.getElementById(cellId);
    
    if (cell.classList.contains('selected')) {
      // Already selected.
      continue;
    }
    
    cell.classList.add('selected');
    cell.innerHTML = '1';
    x++;
  }

}


function tableMatrix () {
  var board, myNumb, myContainer, table;
  
  // Form values.
  board  = document.forms["myForm"]["board"].value;;
  myNumb = document.forms["myForm"]["myNumb"].value;
  
  myContainer = document.getElementById('myContainer');
  myContainer.innerHTML = '';

  // Create table.
  table = createTable(board);

	myContainer.appendChild(table);
  
  selectRandomCells(board, myNumb);
};
table {
  width: 100%;
}

table, td {
   border: 1px solid black;
}

td.selected {
  background: #ccc;
}
    <form name="myForm" method="post">
        <label>Row & Columns Number</label>
        <br/>
        <input type="number" name="board" value="10" placeholder="Number of rows">
        <br/><br/>
        <label>Number of selected cells</label>
        <br/>
        <input type="number" name="myNumb" value="10" placeholder="Number of selected cells">
        <br/><br/>
        <input type="button" value="submit" onclick="tableMatrix()">
    </form>
    
        <div id="myContainer"></div>

答案 2 :(得分:0)

你走了。

function selectRandomCells(board, myNumb, table) {
var totalCells = board * board;
var selectedCell, cellIndex = null;
for(var i=1; i<=myNumb; i++) {
  cellIndex = Math.floor((Math.random() * totalCells) + 1);
  selectedCell = table.rows[Math.floor(cellIndex/board)].cells[cellIndex%board];
  selectedCell.innerHTML = "<span>0</span>";
  if(i == 1) {
    selectedCell.innerHTML = "<span>1</span>";
  }
}
}

演示已更新&gt; https://jsfiddle.net/souravb/9ot5ryf3/5/

p.s:我没有包含重复随机数的逻辑。为此,您只需将随机数存储在一个数组中,并在每次生成新数字时进行检查。