我有一个代码,实际上是一个数学表编码器。如果有人按下按钮,该函数将被调用并运行。但是当我单击按钮时,该表将出现在一个新页面上,而不是在同一页..
<!doctype html>
<html>
<head>
<title>Tafel Trainer</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<section id="content">
<p>Wilt u de tafels leren? Klik op de knop oefenen</p>
<button id="oefenen" name="oefenen" value="oefenen" onclick='oefenen()';>Tafel oefenen!</button>
<div id="1">
<script type='text/javascript'>
function oefenen(){
var num = prompt("Zet een cijfer neer", "0");
var num1 = parseInt(num);
for(i= 1; i< 11; i++) {
document.writeln("<table border='1'><tr><td>" + i + " x " + num1 + " = " + i * num1 + "<br/></td></tr></table>");
}
}
</script>
</div>
</section>
</body>
</html>
我已经尝试使用 document.getElementByID('div1').innerHTML = i;但是该代码也不起作用,我确定这是初学者的错,但是 :)?
提前致谢!
最佳答案
如果你的表格有一个 div
占位符,你将可以更好地控制你正在做的事情,例如
function oefenen(){
var num = prompt("Zet een cijfer neer", "0");
var num1 = parseInt(num);
var table = document.getElementById("tablebody");
for(var i= 1; i< 11; i++) {
var td = document.createElement("td"); //create TD
td.innerHTML = i + " x " + num1 + " = " + (i * num1);
var tr = document.createElement("tr");
tr.appendChild(td); //add TD to the TR
table.appendChild(tr); //add TR to the table
}
//show the placeholder
document.getElementById("placeholder").style.display = "";
}
<section id="content">
<p>Wilt u de tafels leren? Klik op de knop oefenen</p>
<button id="oefenen" name="oefenen" value="oefenen" onclick='oefenen()';>Tafel oefenen! </button>
<div id="1"> <!-- I'm not sure what you use this div for -->
</div>
<div id="placeholder" style="display:none;"> <!-- Placeholder area -->
<table border="1" id="tablebody"></table>
<div>
</section>
还要注意我如何在循环中 var
i
- 否则你会在窗口级别创建对 i
的引用,而不是只是作用域的功能。
此外,createElement
的使用可能看起来冗长 - 但是当您开始创建任何复杂的标记时,它比设置 innerHTML 和连接字符串等更受欢迎。这当然更容易跟踪正在发生的事情并将部分分解为其他功能。
关于javascript - 动态创建的 HTML 表格打开新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27147301/