Issue
I am trying to make a project that includes lives, and to do that I have these three functions in the Javascript code:
{
var lives = 0;
var function1 = lives + 1;
var function2 = Math.pow(lives, 3);
var function3 = function1 * 2;
}
function addLife()
{
document.getElementById("lives").innerHTML = "Lives: " + function1;
}
function prize1()
{
document.getElementById("lives").innerHTML = "Lives: " + function2;
}
function prize2()
{
document.getElementById("lives").innerHTML = "Lives: " + function3;
}
<h1>Welcome!</h1>
<hr/>
<p id="lives">Lives: 0</p>
<input type=button value="Don't click" onClick="addLife()" />
<input type=button value="Prize 1" onClick="prize1()" />
<input type=button value="Prize 2" onClick="prize2()" />
When I run the code the global variable lives does not update. How do I update the variable every time a button is clicked?
Solution
You can try this way:
let lives = 0;
const function1 = () => ++lives;
const function2 = () => lives = Math.pow(lives, 3);
const function3 = () => lives = (++lives) * 2;
function addLife() {
document.getElementById("lives").innerHTML = "Lives: " + function1();
}
function prize1() {
document.getElementById("lives").innerHTML = "Lives: " + function2();
}
function prize2() {
document.getElementById("lives").innerHTML = "Lives: " + function3();
}
<head>
<meta charset="utf-8" />
<title>A very safe site</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Welcome!</h1>
<hr/>
<p id="lives">Lives: 0</p>
<input type=button value="Don't click" onClick="addLife()" />
<input type=button value="Prize 1" onClick="prize1()" />
<input type=button value="Prize 2" onClick="prize2()" />
<!-- Load JS later so HTML loads quickly -->
<script type="text/javascript" src="script.js"></script>
</body>
</html>
Answered By - EzioMercer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.