Before I specify what I am struggling with, let me show you my JavaScript codes.
var gVar = 0;
$("#plus").click(function(e) {
e.preventDefault();
gVar = gVar + 1;
alert(gVar);
});
$("#minus").click(function(e) {
e.preventDefault();
gVar = gVar + 1;
alert(gVar);
});
In the code above, I first set a global variable 'gVar' that holds a integer value of zero. Whenever I click a button whose ID is "plus", the value of the global variable 'gVar' is going to increment by 1, which will be printed out in a browser's dialogue box.
The same thing will happen for the button whose ID is "minus" except that the value of 'gVar' is going to decrement by 1.
In my attempt to tidy up the code above, I created a function separately, which will be called whenever I click the two buttons. Here are the code.
var gVar = 0;
var weird = function (button, Var, num1) {
$(button).click(function(e){
e.preventDefault();
Var = Var + num1;
alert(Var);
});
};
weird("#plus", gVar, 1);
weird("#minus", gVar, -1);
When I run this code, the value of 'gVar' never changes and always stays '0'.
I think I vaguely know what the issue here is, but not entirely sure what is causing this problem. Any input will greatly be appreciated to clarify this issue for me.
Also, I am curious as to if there is any way to create a function to achieve the same effect instead of writing a similar set of code twice for the two different click events.