开发者

Javascript Variables - A variable variable is required

开发者 https://www.devze.com 2023-04-08 20:35 出处:网络
The following code requires that the name of 2 variables are combined. var myScroll; var orderit; var id;

The following code requires that the name of 2 variables are combined.

var myScroll; 
var orderit;
var id;   
$('.scrollable').each(function(){
    orderit += 1;
    $(this).开发者_开发问答attr('id', 'scrollp' + orderit);
    id = $(this).attr('id');
    myscroll = new iScroll( id );
});

So the problem is that the variable my scroll must be unique each time, so its name needs to be myscroll+orderit but I cannot name a variable like that.

Any ideas how to do this.

Marvellous


Make myScroll an array, and push() onto it:

var myScroll = [];

var orderit;
var id;   
$('.scrollable').each(function(){
   orderit += 1;
   $(this).attr('id', 'scrollp' + orderit);
   id = $(this).attr('id');

   // push another iScroll() onto myScroll
   myScroll.push(new iScroll( id ));
 });

Note: In your code, you declared myScroll but later use myscroll. Check the case difference - I fixed it in my example.


Trying to dynamically generate variables is the wrong approach. It can be done (though not in "strict mode"), but it isn't advised.

Instead, you should be creating a collection. You could either use an Array or an Object.


With an Array, you can use .map() to build a collection. Then use .toArray() to generate an Array.

var orderit = 0;
var myScroll = $('.scrollable').map(function(){
    this.id = 'scrollp' + (++orderit);
    return new iScroll( this.id );
}).toArray();

...and access them like:

myScroll[0];
myScroll[1];
  // ...and so on

If you instead want the myScroll1, myScroll2 names, then use an Object.

var orderit = 0;
var scrolls = {};
$('.scrollable').each(function(){
    this.id = 'scrollp' + (++orderit);
    scrolls[ 'myScroll' + orderit ] = new iScroll( this.id );
});

...and access them like:

scrolls.myScroll1;
scrolls.myScroll2;
  // ...and so on

FYI: There's no need for .attr() to get and set the ID of an element. Just access it directly with this.id as I did in my answer.


EDIT: I used the wrong value to build the object properties. Fixed.

0

精彩评论

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

关注公众号