JQuery - reset variable

I have a variable on a webpage that receives a value and has a type string. When the button is pressed, it calls the function and at the end of the function, I would like to clear everything that was installed earlier. I tried using:

$.removeData(myVar);

but he does nothing. The log statements before and after this statement show that it still matters and type, both before and after the above statement.

Another unused variable has a value undefinedand type undefined. Both of these variables are global variables on the page.

How do you reset myVarto its original state? I know this should be easy, but I'm missing something. Would thank for any help.

+4
source share
4 answers

Well ... a few possible direct answers.

myVar = undefined;
myVar = null;
delete window.myVar;

HOWEVER, I would question the logic of having a global variable, but it can only be used in certain methods. Here, how best to structure (with a random pseudo-example of adding values ​​from ajax):

addAjaxButton.onClick(function() {
  var counter = 0;
  ajax(function(addition) {
    counter += addition;
    ajax(function(moreAdd) {
      counter += moreAdd;
      alert('Total is ' + counter);
    });
  });
});

In this case, the counter does not need to be deleted - it will just go out of scope when all AJAX is complete.

+12
source

Just give it a value. If the initial state was undefined, set it to null. You do not need to do anything with jQuery to kill the value.

+1
source

, " " , ?

, .

,

reset myVar ?

What you really want to do is copy it to a local area with a variable and not change the global one. This code demonstrates the use of function parameters and making a copy of the global var locally.

var someGlobal = 1;
someMethod();
someOtherMethod(someGlobal);

function someMethod() {
  var localVar = someGlobal;
  localVar = 2;
}

function someOtherMethod(localVar) {
  localVar = 3;
}

window.console.log(someGlobal);
0
source

This will be a way to reset the values:

$(myVar).val('');
-2
source

All Articles