当我按下按钮时如何防止这种情况发生?
而不是在上面的其他输出下方打印,我希望它替换已经存在的内容。
首次点击:
第二次点击:
代码:
var sq = "";
var outSquare = document.getElementById("outSquare");
var inSquare = document.getElementById("inSquare");
var bSquare = document.getElementById("bSquare");
bSquare.onclick = function () {
var g = inSquare.value;
outSquare.innerHTML = square(g);
}
function square(a) {
for (var i = 1; i <= a; i++ ) {
for (var j = 1; j <= a; j++) {
sq += "*";
}
sq += "<br>";
}
return sq;
}
<p id="outSquare"></p>
<input id="inSquare" type="number"/>
<button id="bSquare" type="button"> Print </button>
答案 0 :(得分:6)
您还需要在函数内部初始化sq
:
var sq = "";
var outSquare = document.getElementById("outSquare");
var inSquare = document.getElementById("inSquare");
var bSquare = document.getElementById("bSquare");
bSquare.onclick = function () {
var g = inSquare.value;
outSquare.innerHTML = square(g);
}
function square(a) {
sq = ""; // empty this string on click
for (var i = 1; i <= a; i++ ) {
for (var j = 1; j <= a; j++) {
sq += "*";
}
sq += "<br>";
}
return sq;
}
<p id="outSquare"></p>
<input id="inSquare" type="number"/>
<button id="bSquare" type="button"> Print </button>
答案 1 :(得分:3)
函数sq = '';
中缺少square(a)
。进行sq=""
会将sq
的值重新初始化为空以进行新的迭代,并输出所需的行为。
var sq = "";
var outSquare = document.getElementById("outSquare");
var inSquare = document.getElementById("inSquare");
var bSquare = document.getElementById("bSquare");
bSquare.onclick = function() {
var g = inSquare.value;
outSquare.innerHTML = square(g);
}
function square(a) {
sq = '';
for (var i = 1; i <= a; i++) {
for (var j = 1; j <= a; j++) {
sq += "*";
}
sq += "<br>";
}
return sq;
}
<p id="outSquare"></p>
<input id="inSquare" type="number" />
<button id="bSquare" type="button"> Print </button>