在HTML中调用一个JavaScript函数两次

前端开发 2026-07-09

我正在尝试在HTML(超文本标记语言)中调用这个JavaScript函数两次。

我的JavaScript代码如下

function test() {
  const scoreDiv = document.getElementById('score')
  let score = parseInt(scoreDiv.innerText);
  score += 1
  scoreDiv.innerText = score.toString()
}

以及我的HTML代码

<html>
<body onload="test();">
<div id="score">0</div>
</body>
</html>

目标是在HTML中让test() 函数被调用两次

我尝试过的做法

<html>
<body onload="test();">
<body onload="test();">
<div id="score">0</div>
</body>
</html>

解决方案

在一个HTML文档中不能使用两个 <body> 标签。
相反,在同一个 onload 内多次调用该函数。

<html>
<body onload="test(); test();">
    <div id="score">0</div>

    <script>
        function test() {
            const scoreDiv = document.getElementById('score');

            let score = parseInt(scoreDiv.innerText);
            score += 1;

            scoreDiv.innerText = score.toString();
        }
    </script>
</body>
</html>

这将在页面加载时调用 test() 两次,因此最终分数将变为 2

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章