[英]How can I print a function from JavaScript to html
I'm trying to make a out of '*' and I got the code right because it works in the console but when I try to print it in the html document it does not work我正在尝试从“*”中提取出来,我得到了正确的代码,因为它在控制台中有效,但是当我尝试在 html 文档中打印它时,它不起作用
function Pyramid() {
let rows = 9;
let output = '';
for (let i = 1; i <= rows; i++) {
for (let j = 1; j <= i; j++) {
output += '* ';
}
console.log(output);
return output;
output = '';
}
}
document.getElementById('pyramid').textContent = generatePyramid();
<body>
<div id="pyramid"></div>
<script src="../script.js/script.js"></script>
</body>
Try this尝试这个
document.getElementById("pyramid").innerHTML='generatePyramid()'; document.getElementById("金字塔").innerHTML='generatePyramid()';
Okay, so there are a few minor issues here.好的,所以这里有一些小问题。
Pyramid
but you are calling generatePyramid
.Pyramid
但您正在调用generatePyramid
。return output
is within the for loop.return output
在 for 循环内。console.log
which will give you a row in the console... however for the HTML you are just dumping it all so it would be a continuous row of stars instead of one row at a time.console.log
输出,这将在控制台中为您提供一行...但是对于 HTML,您只是将其全部转储,因此它将是一排连续的星星,而不是一次一行。 In the code below I've fixed these issues and made it so it outputs each row in a <p>
.在下面的代码中,我已经修复了这些问题并使其在
<p>
中输出每一行。 There are numerous ways to achieve this result and improve upon it, but I think this is what you were aiming for.有很多方法可以实现并改进它,但我认为这就是您的目标。
function generatePyramid() {
let rows = 9;
let output = "";
for (let i = 1; i <= rows; i++) {
output += "<p>";
for (let j = 1; j <= i; j++) {
output += "* ";
}
output += "</p>";
}
return output;
}
document.getElementById("pyramid").innerHTML = generatePyramid();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.