下面的代码要求组合两个变量的名称。
var myScroll;
var orderit;
var id;
$('.scrollable').each(function(){
orderit += 1;
$(this).attr('id', 'scrollp' + orderit);
id = $(this).attr('id');
myscroll = new iScroll( id );
});所以问题是变量my scroll每次都必须是唯一的,所以它的名称必须是myscroll+orderit,但我不能这样命名变量。
有什么好办法吗?
太棒了
发布于 2011-09-28 23:41:56
尝试动态生成变量是错误的方法。这是可以做到的(虽然不是在“严格模式”下),但不建议这样做。
相反,您应该创建一个集合。您可以使用Array或Object。
使用数组,您可以使用.map()来构建集合。然后使用.toArray()生成一个数组。
var orderit = 0;
var myScroll = $('.scrollable').map(function(){
this.id = 'scrollp' + (++orderit);
return new iScroll( this.id );
}).toArray();...and访问它们的方式如下:
myScroll[0];
myScroll[1];
// ...and so on如果您想要myScroll1, myScroll2名称,那么使用一个对象。
var orderit = 0;
var scrolls = {};
$('.scrollable').each(function(){
this.id = 'scrollp' + (++orderit);
scrolls[ 'myScroll' + orderit ] = new iScroll( this.id );
});...and访问它们的方式如下:
scrolls.myScroll1;
scrolls.myScroll2;
// ...and so on仅供参考:.attr()不需要获取和设置元素的ID。只需直接使用this.id访问它,就像我在答案中所做的那样。
编辑:我使用了错误的值来构建对象属性。已修复。
发布于 2011-09-28 23:21:13
将myScroll设置为数组,然后对其执行push()操作:
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 ));
});注意:在您的代码中,您声明了myScroll,但后来使用了myscroll。检查大小写差异-我在我的示例中修复了它。
https://stackoverflow.com/questions/7585482
复制相似问题