如何在HTML中两次调用同一个JavaScript函数?
首先,你之前的写法错误在于HTML文档里只能有一个<body>标签,重复写多个<body>不符合规范,浏览器只会解析第一个,所以第二个onload完全不会生效。
下面是几种可行的正确实现方式:
方法1:在onload属性里直接连续调用两次函数
直接在同一个onload里用分号分隔两次test()调用,页面加载完成后会依次执行:
<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>
方法2:封装新函数统一调用两次test
如果后续需要复用“调用两次test”的逻辑,可以封装一个新函数,再在onload里调用这个新函数:
<html> <body onload="callTestTwice();"> <div id="score">0</div> <script> function test() { const scoreDiv = document.getElementById('score') let score = parseInt(scoreDiv.innerText); score += 1 scoreDiv.innerText = score.toString() } function callTestTwice() { test(); test(); } </script> </body> </html>
方法3:使用事件监听(更推荐的解耦写法)
把JS代码和HTML结构分离,用window.addEventListener监听load事件,在回调里调用两次test,这种写法更符合现代前端开发规范:
<html> <body> <div id="score">0</div> <script> function test() { const scoreDiv = document.getElementById('score') let score = parseInt(scoreDiv.innerText); score += 1 scoreDiv.innerText = score.toString() } // 页面加载完成后执行 window.addEventListener('load', () => { test(); test(); }); </script> </body> </html>
内容的提问来源于stack exchange,提问作者theonatr07
相关产品推荐
相关产品推荐

