2017-09-23 118 views
-1

这是用于生成网格的html代码。当提交按钮被击中时,它会生成一个新的网格并将其添加到旧网格的末端。每次点击按钮时生成一个新的网格

<form id="sizePicker"> 
    Grid Height: 
    <input type="number" id="input_height" name="height" min="1" value="1"> 
    Grid Width: 
    <input type="number" id="input_width" name="width" min="1" value="1"> 
    <button id="Button" type="button">submit</button> 
</form> 
<h2>Design Canvas</h2> 
<table id="pixel_canvas"></table> 

这是使用的JavaScript代码。

const inputHeight = $('#input_height'); 
const inputWidth = $('#input_width'); 
function makeGrid() { 
    const height = parseInt(inputHeight.val()); 
    const width = parseInt(inputWidth.val()); 
    for(let row = 0; row < height; row++) { 
     const tr = $('<tr></tr>'); 
     for(let cell = 0; cell < width; cell++) { 
      tr.append('<td></td>'); 
     } 
     $('#pixel_canvas').append(tr); 
    } 
} 
$('#Button').on('click', makeGrid); 

我们该如何解决这个问题?

+1

需要解决什么问题?你的具体问题和疑问是什么? –

+0

另外,发布所有相关的代码。 '#pixel_canvas'在哪里? –

+0

另外,你实际上没有'submit'按钮(这很好,因为你实际上没有提交任何数据)。你有一个“按钮”按钮。 –

回答

0

您使用jQuery append()这确实你说什么 - 添加新行到现有的元素:在一套匹配

插入内容,由参数指定,每个元素 结束元素。

您需要要么是空的元素追加,甚至更好之前,生成新的内容,比使用jQuery html()方法来设置元素的HTML:

const inputHeight = $('#input_height'); 
const inputWidth = $('#input_width'); 
function makeGrid() { 
    const height = parseInt(inputHeight.val()); 
    const width = parseInt(inputWidth.val()); 
    var newGridHtml = ''; /* Here we generate grid HTML */ 
    for(let row = 0; row < height; row++) { 
     newGridHtml += '<tr>'; 
     for(let cell = 0; cell < width; cell++) { 
      newGridHtml += '<td></td>'; 
     } 
     newGridHtml += '</tr>'; 
    } 
    $('#pixel_canvas').html(newGridHtml); /* No appending here */ 
} 
$('#Button').on('click', makeGrid); 

html()做的是:

获取匹配的 元素集合中第一个元素的HTML内容或设置每个匹配元素的HTML内容。

相关问题