我有這樣的代碼:使用Javascript - 更改變量名
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更改對象名稱。
任何想法如何以更緊湊的方式編寫所有這些代碼?
有人來綁定使用建議'eval'。別。這是一個不好的習慣,有更好的方法。 – Blazemonger