I have this code and no matter what I cannot get the number to increase:
$(".next").click(function (e) {
console.log(e)
var number = 0;
$(".numvalue").text(number );
});
I can see the event getting logged in the console each time I click but the number does not increase. Why would this be the case?
I am using Linux Mint 20.3 and Firefox 101.0.1
CodePudding user response:
The quick fix is to declare number
outside of the function. Declaring it inside means that it gets reset to 0
every time the event happens:
var number = 0;
$(".next").click(function (e) {
$(".numvalue").text(number );
});
The better solution would be to avoid the need for the global variable at all. You can do this by providing a function to text()
which accepts the current value as an argument and returns the new value based on that:
$(".next").click(() => $(".numvalue").text((i, t) => ( t || 0) 1));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button >Next</button>
<span >0</span>
CodePudding user response:
You need to put the variable declaration outside the method, like this
var number = 0;
$(".next").click(function (e) {
console.log(e)
$(".numvalue").text(number );
});