I have a variable in a web page that gets set to a value and is of type string. When a button is clicked, it calls a function & at the end of the function, I would want to clean up anything that had been set previously. I have tried using:
$.removeData(myVar);
but it doesn't do anything. Log statements before & after that statement show that it still has the value & type both before & after the above statement.
Another unused variable has a value of undefined
and a type of undefined
. Both these variables happen to be global variables in the page.
How do you reset myVar
to its initial state? I know it ought to be simple, but I'm missing something. Would appreciate any help.
Well...several possible direct answers.
myVar = undefined;
myVar = null;
delete window.myVar;
HOWEVER, I would question the logic of having the variable be global, but only be used in certain methods. Here's how it might be better to structure (with a random pseudo-example of adding up values from ajax):
addAjaxButton.onClick(function() {
var counter = 0;
ajax(function(addition) {
counter += addition;
ajax(function(moreAdd) {
counter += moreAdd;
alert('Total is ' + counter);
});
});
});
In that case, counter doesn't need to be deleted - it will just go out of scope when all AJAX is complete.
Just assign a value to it. If the initial state was undefined, set it to null. You don't have to do anything fancy with jQuery to kill the value.
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