*已解决* 单击按钮后如何执行功能?
*SOLVED* How to execute a function after a button is clicked?
我试图在每次单击 buttonA
时从 lives
变量中减去 1 条生命。但是 removeLives();
函数在单击 buttonA
之前执行。
<html lang="en">
<body>
<div id="lives"></div>
<button id="buttonA" onClick="removeLives()">buttonA</button>
<script>
var lives = 3;
document.getElementById("lives").innerHTML="LIVES: " + removeLives();
document.getElementById("buttonA").onClick = function(){
removeLives() {
lives--;
return lives;
}
}
</script>
</body>
</html>
当解释器运行 .innerHTML="LIVES: " + removeLives();
行时,removeLives
将被调用,导致 lives
递减,新的内容会减少。
改为将该行放在点击处理程序中,并最初通过 HTML.
填充 lives
div
此外,要么在 HTML 中使用内联处理程序,要么在 JS 中使用 .onclick
,但不能同时使用这两种处理程序 - 最好避免使用内联处理程序,因为它们被普遍认为是不良做法。要在 JS 中添加处理程序,请确保使用 .onclick
,而不是 .onClick
,它区分大小写。
一旦 lives
达到 0,您可能还想停止递减。
var lives = 3;
document.getElementById("buttonA").onclick = function() {
lives--;
if (lives < 0) lives = 0;
document.getElementById("lives").innerHTML = "LIVES: " + lives;
};
<div id="lives">LIVES: 3</div>
<button id="buttonA">buttonA</button>
我试图在每次单击 buttonA
时从 lives
变量中减去 1 条生命。但是 removeLives();
函数在单击 buttonA
之前执行。
<html lang="en">
<body>
<div id="lives"></div>
<button id="buttonA" onClick="removeLives()">buttonA</button>
<script>
var lives = 3;
document.getElementById("lives").innerHTML="LIVES: " + removeLives();
document.getElementById("buttonA").onClick = function(){
removeLives() {
lives--;
return lives;
}
}
</script>
</body>
</html>
当解释器运行 .innerHTML="LIVES: " + removeLives();
行时,removeLives
将被调用,导致 lives
递减,新的内容会减少。
改为将该行放在点击处理程序中,并最初通过 HTML.
填充lives
div
此外,要么在 HTML 中使用内联处理程序,要么在 JS 中使用 .onclick
,但不能同时使用这两种处理程序 - 最好避免使用内联处理程序,因为它们被普遍认为是不良做法。要在 JS 中添加处理程序,请确保使用 .onclick
,而不是 .onClick
,它区分大小写。
一旦 lives
达到 0,您可能还想停止递减。
var lives = 3;
document.getElementById("buttonA").onclick = function() {
lives--;
if (lives < 0) lives = 0;
document.getElementById("lives").innerHTML = "LIVES: " + lives;
};
<div id="lives">LIVES: 3</div>
<button id="buttonA">buttonA</button>