gpt4 book ai didi

javascript - 覆盖段落button.onclick()

转载 作者:太空宇宙 更新时间:2023-11-04 13:50:27 25 4
gpt4 key购买 nike

按下按钮时如何防止这种情况发生?

我不想在上面的其他输出下方打印,而是希望它替换已经存在的内容。

第一次点击:

第二次点击:

代码:

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>

最佳答案

你也需要在函数内部初始化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>

关于javascript - 覆盖段落button.onclick(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52387421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com