<分区>
标签 javascript html css
<分区>
如果我只是链接脚本以在加载 html 页面后启动,它会按照我想要的方式运行 javascript 并在同一页面中输出结果,但是如果我将脚本链接到按钮,它会输出代码到一个单独的 html 页面,上面只有输出。
<body>
<p>Creates a simple multiplication table asking the user to input the number of rows and columns that they want.</p>
<button onclick="myFunction()" class="button_1" >Start Table</button>
<div id="resultDiv"></div>
<script type="text/javascript">
function myFunction(){
var rows = prompt("How many rows for your multiplication table?");
var cols = prompt("How many columns for your multiplication table?");
if(rows == "" || rows == null)
rows = 10;
if(cols== "" || cols== null)
cols = 10;
createTable(rows, cols);
function createTable(rows, cols)
{
var j=1;
var output = "
<table border='1' width='465' cellspacing='0'cellpadding='5'>";
for(i=1;i<=rows;i++)
{
output = output + "
<tr>";
while(j<=cols)
{
output = output + "
<td>" + i*j + "</td>";
j = j+1;
}
output = output + "
</tr>";
j = 1;
}
output = output + "
</table>";
onclick = document.write(output);
}
document.getElementById("resultDiv").innerHTML = total;
}
</script>
</body>
我希望表格的输出显示在按钮所在的下方,但仅在按下按钮并使用提示输入两个变量之后。虽然我在使用按钮时得到的只是重定向到一个单独的 html 页面。
最佳答案
const resultDiv = document.getElementById('resultDiv');
function myFunction() {
let rows = prompt('How many rows for your multiplication table?');
let cols = prompt('How many columns for your multiplication table?');
if (rows == '' || rows == null) rows = 10;
if (cols == '' || cols == null) cols = 10;
resultDiv.innerHTML = createTable(rows, cols);
}
function createTable(rows, cols) {
let j = 1;
let output = ` <table
border = "1"
width = "465"
cellspacing = "0"
cellpadding = "5" > `;
for (let i = 1; i <= rows; i++) {
output += `<tr>`;
while (j <= cols) {
output += `<td>${i * j}</td>`;
j = j + 1;
}
output += `</tr>`;
j = 1;
}
output += `</table>`;
return output;
}
<html>
<body>
<p>
Creates a simple multiplication table asking the user to input the number of rows and columns that they want.
</p>
<button onclick="myFunction()" class="button_1">Start Table</button>
<div id="resultDiv"></div>
</body>
</html>
关于javascript - 如何在给出提示后将函数的结果输出到同一个 HTML 页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53926374/