Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
683 views
in Technique[技术] by (71.8m points)

jquery - javascript - dynamic variables

Hi I am trying to make dynamic variables but it is saying `variable v0 (through to v5) is not defined.

td.each(function(i){
eval('var v' + i + ' = '' + $(this).html() + '';' );
});

any help would be muchly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Oh my.

If you want to create a global "dynamic variable" you should not use var. In this context it creates a variable that is local inside of the each-function, which is quite useless (and will cause it to be undefined outside of the loop, which is what you're experiencing). Instead you should do it like this:

td.each(function(i){
  window['v' + i] = $(this).html();
});

The downside with the above code is that global variables are not really great either.

On the other hand, if you want a local variable (if for example there will be more code in the loop that uses this varaible, then I would do it like this:

td.each(function(i){
  var dynVars = {};
  dynVars['v' + i] = $(this).html();

  alert(dynVars.v4); // use the dynamic variables by saying "dynVars.NAME"

});

You could combine these two solutions, by putting the declaration of dynvars (var dynVars = {}) in the scope where you want to be able to access your variables instead. As long as it is also visible in this each-callback, everything will work out fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...