[英]How can I get this loop's information in a table (Javascript)
I'm trying to get the loop that is in the code after this text to have the information outputted into a table. 我正在尝试获取此文本后代码中的循环,以将信息输出到表中。 To explain this further, the function
function doEvens()
creates a loop that takes uses the number a person enters into the input text box Type in your Number: <input type="number" id="num">
, and displays all even numbers between that number and 2 within a paragraph: <p id="space"></p>
, when the numbers are displayed within the paragraph they have a semicolon and a space separating them, instead of that I would like the numbers to be within a table, I have tried using createElementById and with no luck, I have tried putting a table between certain areas of the code, with no luck I still have not been able to fix this, I have many other projects I am working on and I am not very good at coding. 为了进一步解释这一点,函数
function doEvens()
创建一个循环,该循环使用一个人在输入文本框中输入Type in your Number: <input type="number" id="num">
,并显示所有偶数在段落中该数字和2之间的数字: <p id="space"></p>
,当数字显示在段落中时,它们具有分号和空格分隔它们,而不是我希望这些数字在一个表中,我尝试使用createElementById,但是没有运气,我试图在代码的某些区域之间放置一个表,但是没有运气,我仍然无法解决此问题,我正在从事许多其他项目而且我不太擅长编码。
<!DOCTYPE html>
<html>
<head>
<script>
function doEvens() {
var number = document.getElementById('num').value;
if(number > 1) {
if(number % 2 == 0) {
while(number > 2) {
document.getElementById("space").innerHTML += (+number - 2) + "; ";
number = +number - 2;
}
} else {
number--;
alert(number);
while(number > 1) {
document.getElementById("space").innerHTML += (+number - 2) + "; ";
number = +number - 2;
}
}
}
}
</script>
</head>
<body>
Type in your Number: <input type="number" id="num">
<button onclick="doEvens();" href="javascript;">Submit</button>
<p id="space"></p>
</p>
</body>
</html>
I have implemented the solution with table
. 我已经用
table
实现了解决方案。 Here it is: 这里是:
function doEvens() { var number = document.getElementById('num').value, table = document.getElementById('evensTable'), cellsInRow = 20, evens = [], tableContent = '', row = '', i = 3, startAt, numberOfRows; table.innerHTML = ''; while (i++ < number - 1) { i % 2 === 0 && evens.push(i); } numberOfRows = evens.length / 20; for (var r = 0; r < numberOfRows; r++) { row = '<tr>'; startAt = r * cellsInRow; for (var c = startAt; c < startAt + cellsInRow; c++) { if (!evens[c]) break; row += '<td>' + evens[c] + '</td>'; } row += '</tr>'; tableContent += row; } table.innerHTML = tableContent; }
<body> Type in your Number: <input type="number" id="num"> <button onclick="doEvens();" href="javascript;">Submit</button> <table id="evensTable"> </table> </body>
This table
contains one row, but you can also create more rows in code (say after every 10 numbers print) 该
table
包含一行,但是您也可以在代码中创建更多行(例如,每打印10个数字后)
If something is not clear for you, please ask me. 如果您不清楚某些事情,请问我。
UPDATE 更新
I have updated the solution as per your needs. 我已根据您的需要更新了解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.