开发者

Create variables dynamically with a For Loop Javascript

开发者 https://www.devze.com 2023-03-29 21:47 出处:网络
The title plus the following example are self-explanatory of what I don\'t achieve :-) The idea is to replace something + counter in order to make it work.

The title plus the following example are self-explanatory of what I don't achieve :-) The idea is to replace something + counter in order to make it work.

      for (var counter = 1; counter <= 6; counter++) {
        var something + counter = $('element' + c开发者_JAVA技巧ounter);
        (something + counter).removeAttribute('class');
      }     


You could create an array, but much more simply:

  for (var counter = 1; counter <= 6; counter++) {
    $('element' + counter).removeAttribute('class');
  } 


Just do:

for (var counter = 1; counter <= 6; counter++) {
    $('element' + counter).removeAttribute('class');
}

Unless you wanted to store it outside of the loop, in which case use an array.


Use an array.

var something = [];
for (var counter = 1; counter <= 6; counter++) {
    something[counter] = $('element' + counter);
    something[counter].removeAttribute('class');
}


Why can't you just get rid of the var altogether??

for (var counter = 1; counter <= 6; counter++) {
    $('element' + counter).removeAttribute('class');
}


  for (var counter = 1; counter <= 6; counter++) {
    window[something + counter] = $('element' + counter);
    window[something + counter].removeAttribute('class');
  } 

after that there will be a set of fields in window object, named something1, something2 etc (if something == "something", of course)

0

精彩评论

暂无评论...
验证码 换一张
取 消