I'm stuck with this code and do not understand why it's not working as I expect. This way, the boolean variable "x" changes its value every time I click the #btn
:
$(document).ready(function() {
var x = false;
$("#btn").click(function() {
toggleBtn(x);
x = !x;
});
function toggleBtn(x) {
if (!x) {
doThis();
} else {
doThat();
}
};
});
But this way, "x" does not change it's value:
$(document).ready(function() {
var x = false;
$("#btn").click(function() {
toggleBtn(x);
});
function toggleBtn(x) {
if (!x) {
doThis();
} else {
doThat();
}
x = !x;
};
});
Why is that?
Because you have two x
variables.
One is declared here:
var x = false;
The other is declared here:
function toggleBtn(x) {
In the first example, you're updating the value of the first x
. In the second example, you're updating the value of the second x
. Which then immediately falls out of scope when the function ends and is destroyed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With