0

我有这个定义随机颜色集的函数。

我的问题是定义变量 ( ) 以从对象var target中选择新的颜色集。kuler

kuler: {
    set0:['#499E8D','#85CC9F','#A4DEAB','#C8E8C7','#FFF6C9'],
    set1:['#0F2440','#2C3F59','#518C8C','#94BEAC','#D9CAAD'],
    set2:['#499E8D','#85CC9F','#A4DEAB','#C8E8C7','#FFF6C9'],
    set3:['#0F2440','#2C3F59','#518C8C','#94BEAC','#D9CAAD'],
    set4:['#499E8D','#85CC9F','#A4DEAB','#C8E8C7','#FFF6C9'],
    set5:['#0F2440','#2C3F59','#518C8C','#94BEAC','#D9CAAD'],
    set6:['#499E8D','#85CC9F','#A4DEAB','#C8E8C7','#FFF6C9']
},
setNewColourSet: function () {
    rn=Math.floor(Math.random()*5);
    for (i=0; i<4; i++){
        var target = "project.kuler.set"+rn+"["+i+"]";
        $('.kuler'+i).css('background-color',target);
        /* works *///  $('.kuler'+i).css('background-color',project.kuler.set4[i]);
    }
}
4

4 回答 4

4

认为你很接近 - 只需将字符串放在方括号内。

var target = project.kuler['set' + rn][i];

假设rn是附加到的数字'set',并且kuler它本身在一个名为 的对象字面量中project

请注意,第一个大括号 ( kuler['set'+rn]) 是对对象字面量的属性访问kuler,第二个大括号 ( [i]) 是对数组的数组索引访问....

于 2012-08-21T13:22:44.773 回答
2
kuler: {
    set0:['#499E8D','#85CC9F','#A4DEAB','#C8E8C7','#FFF6C9'],
    set1:['#0F2440','#2C3F59','#518C8C','#94BEAC','#D9CAAD'],
    set2:['#499E8D','#85CC9F','#A4DEAB','#C8E8C7','#FFF6C9'],
    set3:['#0F2440','#2C3F59','#518C8C','#94BEAC','#D9CAAD'],
    set4:['#499E8D','#85CC9F','#A4DEAB','#C8E8C7','#FFF6C9'],
    set5:['#0F2440','#2C3F59','#518C8C','#94BEAC','#D9CAAD'],
    set6:['#499E8D','#85CC9F','#A4DEAB','#C8E8C7','#FFF6C9']
},
setNewColourSet: function () {
    var rn = Math.floor(Math.random()*5);

    for (i=0; i<4; i++){
    $('.kuler'+i).css('background-color', this.kuler['set'+i][rn]);
    }
}

干得好

于 2012-08-21T13:28:38.730 回答
1

如果您要拥有一个像这样带有编号名称的对象,为什么不只是一个列表呢?

kuler: [
  ['#499E8D','#85CC9F','#A4DEAB','#C8E8C7','#FFF6C9'],
  ['#0F2440','#2C3F59','#518C8C','#94BEAC','#D9CAAD'],
  ['#499E8D','#85CC9F','#A4DEAB','#C8E8C7','#FFF6C9'],
  ['#0F2440','#2C3F59','#518C8C','#94BEAC','#D9CAAD'],
  ['#499E8D','#85CC9F','#A4DEAB','#C8E8C7','#FFF6C9'],
  ['#0F2440','#2C3F59','#518C8C','#94BEAC','#D9CAAD'],
  ['#499E8D','#85CC9F','#A4DEAB','#C8E8C7','#FFF6C9']
],

setNewColourSet: function () {
  rn=Math.floor(Math.random()*5);
  for (i=0; i<4; i++){        
    $('.kuler'+i).css('background-color',kuler[rn][i]);
  }
}
于 2012-08-21T13:26:50.280 回答
0

var target = "project.kuler.set"+rn+"["+i+"]";

您正在将字符串分配给目标。

我想 project 是一个对象,而 kuler 是它的一部分,所以尝试删除引号;

于 2012-08-21T13:27:46.393 回答