如何使我的循环从0开始而不是1 ?



谁能告诉我如何调整这个表格以包含一个" heading ";让表的值从1开始,而不是0。这些值应该像这样添加:

1  2  3  4  5  
2  4  6  8  10
3  6  9  12 15
4  8  12 16 20
5  10 15 20 25

谢谢!

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Table</title>
<style>
body {
margin: 27px;
}
</style>
</head>
<body>
<script>
function createTable() {
rn = window.prompt("Input number of rows");
cn = window.prompt("Input number of columns");
for (var r = 0; r < parseInt(rn, 10); r++) {
var x = document.getElementById("myTable").insertRow(r);
for (var c = 0; c < parseInt(cn, 10); c++) {
var y = x.insertCell(c);
y.innerHTML =  + r +  + c;
}
}
}
</script>
<table id="myTable" border="1"></table>
<form>

<input type="button" onclick="createTable()" value="Create the table"/>


</form>
<h1>To create your own table, please click the create table button.</h1>
</body>
</html>

你似乎有三个问题,都有简单的解决方案:

  • 您缺少一个标题行。只需在创建其余行的循环之前添加一个。你可以用createTHead代替insertRow。它没有insertCell虽然,所以你需要手动创建和附加<th>元素。
  • 你的值从0开始而不是1。为什么不简单地+1这些值呢?或者从1开始,而不是0?
  • 你的数学公式错了。那为什么不改呢?

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Table</title>
<style>
body {
margin: 27px;
}
</style>
</head>
<body>
<script>
function createTable() {
rn = window.prompt("Input number of rows");
cn = window.prompt("Input number of columns");

const table = document.getElementById("myTable"); // gonna use it several times
table.innerHTML = ''; // Empty the table

// Add the head and fill it with cells
const head = table.createTHead();
for (let i = 1; i <= cn; i++) {
const th = document.createElement('th');
th.innerText = i;
head.appendChild(th);
}
// Add all the rows and cells
for (var r = 1; r <= parseInt(rn, 10); r++) {
var x = table.insertRow(); // no need for an index if it's just to append
for (var c = 1; c <= parseInt(cn, 10); c++) {
var y = x.insertCell(); // no need for an index if it's just to append
y.innerText =  r * c; // changed the formula
}
}
}
</script>
<table id="myTable" border="1"></table>
<form>

<input type="button" onclick="createTable()" value="Create the table"/>


</form>
<h1>To create your own table, please click the create table button.</h1>
</body>
</html>

相关内容

最新更新