从两个输入字段创建div网格

时间:2019-07-31 21:55:45

标签: javascript html css

给出两个输入字段,我想创建一个网格,将第一个输入作为行,第二个输入作为列,并在单击单独的按钮后出现。

我知道如何制作网格NxN,但是我想要一个网格NxY,它专门通过按钮创建。

const grid = document.querySelector("#gridDiv");
const rowSize = document.querySelector("#rowInput");
const colSize = document.querySelector("columnInput");
const button = document.querySelector("button");

function NxY(n, y) {
  let rowsArr = [];
  let columnArr = [];
  for (let i = 0; i < n; i++) {
    columnArr.push(i);
  }
  for (let i = 0; i < y; i++) {
    rowsArr.push(columnArr);
  }
  render(rowsArr)
}

function render(arr) {
  arr.forEach((items) => {
    let outerDiv = document.createElement("div")
    outerDiv.classList.add("row");
    items.forEach((item) => {
      let dv = document.createElement("div");
      dv.classList.add("cell");
      outerDiv.appendChild(dv);
    });
    grid.appendChild(outerDiv);
  });
}
NxY(3, 4);

这将自动生成底部指定的网格,但是我的问题是弄清楚如何向按钮添加eventListener,以正确地引导它创建正确的网格。

1 个答案:

答案 0 :(得分:1)

尝试此代码段

$('#btnInsert').click(function(){
$('#mtable tbody').html('');
var row_count = $('#row').val();
var col_count = $('#col').val();
    if(row_count && col_count){
     //entry is valid
    while(row_count > 0){
     //add new row
        $('#mtable tbody').append($("<tr>"));  
      row_count--;
        }
        while(col_count > 0){
        //add new column
        $('#mtable tr').append($("<td>")); 
        $('#mtable tbody tr').each(function(){$(this).children('td:last').append($('<input type="checkbox">'))});
      col_count--;
        }
    }else{alert('Invalid entry');}
}); 

$('#btnInsert2').click(function(){
$('#mDiv').html('');
var row_count = $('#row2').val();
var col_count = $('#col2').val();
    if(row_count && col_count){
     //entry is valid
    while(row_count > 0){
     //add new row
        $('#mDiv').append($("<div class='row'>"));  
      row_count--;
        }
        while(col_count > 0){ 
        //add new column
        $('#mDiv').children('.row').each(function(){$(this).append($('<div class="col col-md-4">'))});
      col_count--;
        }
    }else{alert('Invalid entry');}
}); 
td{padding:5px;}
.col{margin:5px;
     min-height: 50px;
     background: #aaaaaa;}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<h3>For Tables </h3>
<input id="row" type="number" max="20" placeholder="Enter no. of rows"/> 
<input id="col" type="number" max="20" placeholder="Enter no. of columns"/>
<button id="btnInsert">Generate Grid</button>
<table border="1" id="mtable"> 
    <tbody></tbody>
</table><br/><br/><br/><br/>


<h3>For Divs </h3>
<input id="row2" type="number" max="20" placeholder="Enter no. of rows"/> 
<input id="col2" type="number" max="20" placeholder="Enter no. of columns"/>
<button id="btnInsert2">Generate Grid</button>
<br>
<div class="container" id="mDiv"></div><br/><br/><br/><br/>