-1

我正在使用用户输入创建一个二维数组。如何在 3 x 3 表上显示输入?

<script language = javascript>
var b = [];
for(var i=0; i<3; i++){
b[i] = [];
for(var j=0; j<3; j++){
b[i][j] = window.prompt("b["+(i+1)+","+(j+1)+"] = ?");
}
}
</script>
</head>
<body>
<table width="80%" border="2" cellspacing="0" cellpadding="0">
  <tr>
<td> </td>
<td>&nbsp;</td>
<td>&nbsp;</td>
 </tr>
 <tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
4

2 回答 2

2

你可以做这样的事情..

<!DOCTYPE html>
<html>
<head>
<style>
table {
    font: 11px/24px Verdana, Arial, Helvetica, sans-serif;
    border-collapse: collapse;
    width: 320px;
    }

td {
    border: 1px solid #CCC;
    padding: 0 0.5em;
    }


</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>

$(document).ready(function(){



$("#myRandomizeBtn").bind("click",randomizeHandler); 

function randomizeHandler(evt){     
var root=document.getElementById('mydiv');
var tab=document.createElement('table');
tab.className="mytable";
var tbo=document.createElement('tbody');
var row, cell;
var n = 3;  
var data;    

for (i=0; i<n; i++)
{
    row=document.createElement('tr');
    for(var j=0;j<n;j++){
        cell=document.createElement('td');
        data =window.prompt("b["+(i+1)+","+(j+1)+"] = ?"); 
        cell.appendChild(document.createTextNode(data));
        row.appendChild(cell);
    }
    tbo.appendChild(row);
}
tab.appendChild(tbo);
root.appendChild(tab);




   }  



});
</script>
</head>
<body>
    <div id='mydiv'></div>
    <button id = "myRandomizeBtn">Randomize</button> 
</body></html>

这是一个工作小提琴

于 2013-10-30T17:01:51.867 回答
1

您可以使用以下代码来遍历和推送值

var table = document.getElementById("mytab1");
for (var i = 0, row; row = table.rows[i]; i++) {
   //iterate through rows
   //rows would be accessed using the "row" variable assigned in the for loop
   for (var j = 0, col; col = row.cells[j]; j++) {
     //iterate through columns
     //columns would be accessed using the "col" variable assigned in the for loop

       col.innerText = b[i][j]; //Set your value here   
   }  
}

Working Demo

来自@John Hartsock 答案的遍历参考如何在 javascript 中遍历表行和单元格?

于 2013-10-30T17:01:01.133 回答