使用用户输入创建Javascript行

Create Javascript rows with user input

本文关键字:Javascript 创建 输入 用户      更新时间:2023-09-26

如何开始为下面提供的代码编写for循环:

<html>
<head>
</head>
<body>
Rows: <input name="rows" id="rows" type="text"/><br/>
<input type="submit" value="Make me a table!" onclick="makeTable();"/><br/><br/>
<table border="1" id="theTable">
</table>
<script type="text/javascript">
function makeTable(){
//Insert code here AND ONLY HERE!
//Write a for loop to create the number of rows specified in the "row" input field
</script>
</body>
</html>

由于我怀疑这是家庭作业,我不会提供完整的代码答案,而是为您提供一些指南,希望能对您有所帮助。

您有html和javascript,为了创建新的html元素,您需要使用document.createElement(type)函数来创建一个新元素,在您的情况下是-td/th?

然后你需要把它插入你的桌子你可以通过获取表(通过id/type)来实现这一点——在网上搜索这个表非常简单。然后在is上使用append方法来处理创建的元素。

您使用一个正常的for循环来完成所有这些过程,该循环将运行到html中输入标记的.value(再次搜索如何获得这些值)

祝你好运=]

这就是您想要的吗?

function makeTable(){
    // Get values of rows/cols inputs
    var rows = document.getElementById('rows').value;
    var cols = document.getElementById('cols').value;
    // Check the values are in fact numbers
    if (!isNaN(rows) && !isNaN(cols)) {
        // Get the table element
        var table = document.getElementById('theTable');
        // Iterate through rows
        for (var r = 0; r < rows; ++r) {
            // Create row element
            var tr = document.createElement('tr');
            // Iterate through columns
            for (var c  = 0; c < cols; ++c) {
                // Create cell element
                var td = document.createElement('td');
                // Setting some text content
                td.textContent = 'R: ' + r + ', C: ' + c;
                // Append cell to row
                tr.appendChild(td);
            }
            // Append row to table
            table.appendChild(tr);
        }
    }
}
<!DOCTYPE html>
<html>
  <head>
<title>test</title>
  <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
 <body>
  Rows: <input name="rows" id="rows" type="text"/><br/>
  Cols: <input name="cols" id="cols" type="text"/><br/>
  <input type="submit" value="Make me a table!" onclick="makeTable();"/>   <br/><br/>
  <table border="1" id="theTable">

  <script type="text/javascript">
  function makeTable(){
   var html = "";
   var row=$('#rows').val();
   var col=$('#cols').val();
   for(var i=0; i<row; i++){
  html+="<tr>";
   for(var j=0;j<col; j++)
   {
       html+= '<td> Your data </td>';
     }
    html+="</tr>"
    }
   $('#theTable').html(html);

    //Insert code here AND ONLY HERE!
    //Write a for loop to create the number of rows specified in the "row" input field
    //create a dom element for the row to be added to the table
  }
   </script>
  </body>
 </html>

我一直保持简单。希望能有所帮助。