如何通过按钮更新HTML文本

How to update HTML text by button?

本文关键字:HTML 文本 更新 按钮 何通过      更新时间:2023-09-26

这就是我迄今为止所取得的成就。有了这个按钮,我可以得到分数加起来的总数。但在Score,它不是每次都更新的。

 <script>
    function True(){
        score5=1;
            alert("Correct");   
        total=score1+score2+score3+score3+score5;
        }
    </script>
    <input type="button" value="True" onClick="True()">
    <h2>Score:<script>document.write(total)</script><h2>

document.write将在浏览器解析页面时运行,远早于True()函数的运行时间。你需要给你的h2一个id,然后用它将其innerHTML设置为True():内的计算分数

// dummy values
var score1 = 5, score2 = 4, score3 = 3, score4 = 2;
function True(){
    score5=1;
    alert("Correct");   
    total=score1 + score2 + score3 + score4 + score5;
    document.getElementById('score').innerHTML = "Score: " + total.toString();
}
<input type="button" value="True" onClick="True()" />
<h2 id="score">Score: 0<h2>

不要有<script>标签,而是有一个<span>标签并给它一个ID:

<h2>Score: <span id="totalscore"></span>

现在让您的函数编辑该跨度的HTML,如下所示:

document.getElementById("totalscore").innerHTML = total;