2017-09-23 47 views
0

我想在html中使用輸入標籤中的數據。 html代碼如下所示。在javascript中使用輸入標籤中的數據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"> 
<input type="submit"> 

從輸入變量的數據值應該在JavaScript代碼如下所示使用:

function makeGrid() { 
    for(let td_row=0; td_row < 6; td_row++){ 
    $(<tr></tr>).appendTo(<table id="pixel_canvas"></table>); 
for(let td_cell =0; td_cell < 6; td_cell++){ 
     $(<td></td>).appendTo(<tr></tr>); 
    } 
    } 

有人可以請幫我在這?

回答

0

試試這個解決方案。從輸入中獲取值並將它們設置爲循環中條件的範圍。然後在第一個循環中添加您的創建tr,在第二個循環中添加td。畢竟追加tr with tds到表中。

const table = $('#pixel_canvas'); 
 
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>${row}${cell}</td>`); 
 
    } 
 
    
 
    table.append(tr); 
 
    } 
 
} 
 
    
 
$('#submitBtn').on('click', makeGrid);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<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="submitBtn" type="button">Generate</button> 
 

 
<table id="pixel_canvas"> 
 

 
</table>

0

您需要使用字符串,創建HTML元素時(例如$( ''))而不是原始標記。我更新了問題中的函數,以便它創建一個表並返回它。您只需將其插入任何需要的地方。

function makeGrid() { 
    var rowsCount = ParseInt($('#input_height').val()) || 0; 
    var columnsCount = ParseInt($('#input_width).val()) || 0; 
    var table = $('<table id="pixel_canvas"></table>'); 

    for(let td_row = 0; td_row < rowsCount; td_row++){ 

    var tr = $('<tr></tr>').appendTo(table); 

    for(let td_cell = 0; td_cell < columnsCount; td_cell++){ 
     $('<td></td>').appendTo(tr); 
    } 

    } 
    return table; 
} 
相關問題