2 回答
TA贡献1813条经验 获得超2个赞
feipigzi 的代码没有给机会输入行列数,而且使用的 createElement 和 appendChild。我还是比较赞成使用较规范的 insertRow 和 insertCell。
1234567891011121314151617181920 | <script type= "text/javascript" > window.onload = function () { document.getElementById( "add" ).onclick = function () { var rows = parseInt(document.getElementById( "rows" ).value), cols = parseInt(document.getElementById( "cols" ).value); if (rows && cols) { var table = document.createElement( "table" ); table.border = 1; for ( var r = 0; r < rows; r++) { var row = table.insertRow(-1); for ( var c = 0; c < cols; c++) { var cell = row.insertCell(-1); cell.innerHTML = "行" + (r + 1) + "列" + (c + 1); } } document.body.appendChild(table); } }; }; </script> |
123 | < input type = "text" size = "4" id = "rows" value = "" /> 行 < input type = "text" size = "4" id = "cols" value = "" /> 列 < input type = "button" id = "add" value = "生成表格" /> |
TA贡献1712条经验 获得超3个赞
你说的表格是指html中的表格么?
<input type="text" id="input"/>
<input id="goBtn" type="button" value="GO"/>
<script>
document.getElementById('goBtn').onclick = function () {
var value = document.getElementById('input').value;
if(!value) return;
var table = document.createElement('table');
table.setAttribute("border", '1px');
document.body.appendChild(table);
for(var i = 0; i < 3; i++) {
var row = document.createElement('tr');
for(var k = 0; k < 4; k++) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(value));
row.appendChild(cell);
}
table.appendChild(row);
}
};
</script>
添加回答
举报