Javascript - 更改变量名称

时间:2014-04-17 21:52:48

标签: jquery

我有这段代码:

if(response.next == "2") {
  $('.imgdiff-1').attr('src', img2.src);
  $('.imgdiff-2').attr('src', img22.src);
}
if(response.next == "3") {
  $('.imgdiff-1').attr('src', img3.src);
  $('.imgdiff-2').attr('src', img32.src);
}
if(response.next == "4") {
  $('.imgdiff-1').attr('src', img4.src);
  $('.imgdiff-2').attr('src', img42.src);
}
if(response.next == "5") {
  $('.imgdiff-1').attr('src', img5.src);
  $('.imgdiff-2').attr('src', img52.src);
}

var level_img_src = "images/levels/";
var img2 = new Image();
img2.src = level_img_src + '2.jpg';
var img22 = new Image();
img22.src = level_img_src + '22.jpg';
var img3 = new Image();
img3.src = level_img_src + '3.jpg';
var img32 = new Image();
img32.src = level_img_src + '32.jpg';
var img4 = new Image();
img4.src = level_img_src + '4.jpg';
var img42 = new Image();
img42.src = level_img_src + '42.jpg';
var img5 = new Image();
img5.src = level_img_src + '5.jpg';
var img52 = new Image();
img52.src = level_img_src + '52.jpg';

我想要而不是所有if语句来做这样的事情:

$('.imgdiff-1').attr('src', img' + response.next + '.src);
$('.imgdiff-2').attr('src', img' + response.next + '2.src);

此代码不起作用,但我想使用来自ajax的变量以dinamically方式更改对象名称。

有任何想法如何以更紧凑的方式编写所有这些代码?

2 个答案:

答案 0 :(得分:0)

将图像放入数组:

img = img2 = []; // empty array
img[2] = new Image();  img[2].src  = level_img_src+'2.jpg';
img2[2] = new Image(); img2[2].src = level_img_src+'22.jpg';
// etc.

然后按索引编号拉出图像:

$('.imgdiff-1').attr('src', img[response.next].src);
$('.imgdiff-2').attr('src', img2[response.next].src);

答案 1 :(得分:0)

尝试这样的事情?:

var img2 = new Image(); im2.src=lvl_img_src+'2.jpg';

... get response...

var imgSrc = response.next + '.src';
$(.imgdiff-1').attr('src', img + imgSrc)