最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Create variables dynamically with a For Loop Javascript - Stack Overflow

programmeradmin2浏览0评论

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' + counter);
        (something + counter).removeAttribute('class');
      }     

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' + counter);
        (something + counter).removeAttribute('class');
      }     
Share Improve this question asked Aug 23, 2011 at 13:16 BrunoBruno 9,07713 gold badges40 silver badges55 bronze badges 2
  • 1 Why not use an array, or apply those changes directly? – Sleeperson Commented Aug 23, 2011 at 13:19
  • 1 Why do you need to create a variable in the loop at all? Can you not just do $('element' + counter).removeAttribute('class');? – James Allardice Commented Aug 23, 2011 at 13:19
Add a ment  | 

5 Answers 5

Reset to default 3

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)

  1. 暂无评论