我正在尝试创建一个具有两个文本框的页面,用户可以在其中选择他们想要的行数和列数。然后根据他们的要求创建一个包含文本框的网格,并添加一列和一行禁用的文本框来计算每行和每列的总和。该函数对所有行求和,但我真的很难对行求和。这是到目前为止的代码。
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=utf-8">
<title></title>
<script>
function grid() {
var row = document.getElementById("rows");
var column = document.getElementById("columns");
row.value = parseInt(row.value);
column.value = parseInt(column.value);
for (var x = 0; x <= parseInt(row.value); x++) {
for (var y = 0; y <= parseInt(column.value); y++){
var br = document.createElement("br");
var box = document.createElement("input")
box.setAttribute("type", "text");
box.setAttribute("size", "5");
box.setAttribute("id", "tb" + x + y);
box.setAttribute("name", "add" + x);
box.setAttribute("value", "0");
box.style.marginRight = "3px";
box.style.marginBottom = "3px";
var output = document.createElement("input");
output.setAttribute("id", "output" + parseInt(x) + parseInt(y))
output.setAttribute("name", "result" + x);
output.setAttribute("disabled", "true");
output.setAttribute("size", "5");
output.style.marginRight = "3px";
if (x < parseInt(row.value)){
if (y < parseInt(column.value)){
document.getElementById("boxs").parentNode.appendChild(box);
}else{
document.getElementById("boxs").parentNode.appendChild(output);
document.getElementById("boxs").parentNode.appendChild(br);
}
}else{
document.getElementById("boxs").parentNode.appendChild(output);
}
}
}
//remove last box
tbid = "output" + (row.value) + (column.value);
nobox = document.getElementById(tbid);
nobox.parentNode.removeChild(nobox);
}
</script>
<script>
function calculate(){
var row = document.getElementById("rows");
var column = document.getElementById("columns");
row.value = parseInt(row.value);
column.value = parseInt(column.value);
var perform = document.getElementById("perform");
for (var x = 0; x < parseInt(row.value); x++) {
var arr = document.getElementsByName("add" + x);
var rowTotal = 0;
var colTotal = 0;
for(var y = 0 ; y < parseInt(column.value); y++){
if(parseInt(arr[y].value))
rowTotal += parseInt(arr[y].value);
}
if(perform.value == "sum"){
document.getElementById("output" + x + y).value = rowTotal;
}else if(perform.value == "mean"){
document.getElementById("output" + x + y).value = rowTotal / parseInt(row.value);
}
}
}
</script>
</head>
<body>
<div>
<div id="boxs">
</div>
<div id="matrix">
Rows<input type="text" id="rows">
Columns<input type="text" id="columns">
<button id="button" onclick="grid()">Create Grid</button><br><br>
<select id="perform">
<option value="sum">sum</option>
<option value="mean">Mean</option>
<option value="mode">Mode</option>
<option value="median">Median</option>
</select><br>
<button id="calculate" onclick="calculate()">Calculate</button><br><br>
</div>
</div>
</body>
我意识到它可能很混乱,但我对此很陌生。任何帮助或指导将不胜感激。提前致谢。