2

Is there a way to "save" a variable in jQuery?

I have an .each() loop that changes the value of sz[1] and fires a .load() for each value. However, when I place sz[1] in the callback function, it only uses the last recorded value of sz[1], and not the value it had when I initially called .load().

$("#Big").find("a").each(function() {
  url = $(this).attr("href");
  pattern = new RegExp("sizes/([" + sizes + "])/$");
  otherPattern = new RegExp("sizes/([" + otherSizes + "])/$");
  sz = pattern.exec(url);
  if(sz) {
    normLink(sz[1], srcBase);
  } else {
    sz = otherPattern.exec(url);
    if(sz) {
      NotOkToDeLoad++;
      $("a#" + sz[1]).load(URL + sz[1] + " div#psp", function() { fixLink(sz[1]); });
    }
  }
});

sz[1] can be "k", "h" or "o". However, fixLink() is always called with that last possible value of "o" three times.

My current workaround is to write three separate .load()'s for each possible value of sz[1], but there ought to be an easier way. Am I overlooking something?

druidic
  • 65
  • 5

4 Answers4

2

Get used to making your variables local, using var [MDN]:

var pattern = new RegExp("sizes/([" + sizes + "])/$");
var otherPattern = new RegExp("sizes/([" + otherSizes + "])/$");
var sz = pattern.exec(url);

Your problem is that sz is (implicitly) global and hence every iteration of the loop overwrites the previous value.

Avoid globals as much as possible. Tools like JSHint will warn you in case of implicit globals.

Also note that there is another problem when creating closures in a loop. It does not apply to your case, since you are using .each() and not a normal for loop, but better be aware of it.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • P.S. I **had** declared the variables with a `var` statement, but they were declared globally. I like to reuse variable names when possible, but yeah, that wasn't very useful for this particular case. – druidic Jun 17 '12 at 10:33
  • @druidic: You're welcome :) If any answer helped you, please click the checkmark next to it, to accept it and to mark your question as solved. – Felix Kling Jun 17 '12 at 10:34
0

Probably you are making global vairable sz try using var keyword.

IProblemFactory
  • 9,551
  • 8
  • 50
  • 66
0

Use closure to save value (only if you can not make sz variable local!):

$("a#" + sz[1]).load(URL+ ...., (function(val) { return function(){ fixLink(val); } })(sz[1]));
Alexander
  • 1,287
  • 1
  • 15
  • 34
  • 2
    He already uses a closure, you are executing a function immediately to create a new scope. Of course said function is also a closure, but this is not relevant here. Anyways, better fix the actual problem: missing `var` statement. – Felix Kling Jun 17 '12 at 10:27
-1

I don't know if it can help, but maybe you can store the variable that you need in a $.data() variable associated to the element... you can read something about this here

MaJac89
  • 151
  • 4