我有一个充满MapIcon的数组,每个数组都包含一个名称和一个图像。

该数组称为mapIcon。

当分别定义每个实例时,我们具有这三个功能,但是当我尝试将其变成一个确定用户单击哪个图像的功能时,就会遇到问题。

mapIcon[0].click(function(){
    var selectedMap = ($('<img src="img/' + maps[0].image + '">'));
    gameplayScreen.append(selectedMap);
    mapSelectScreen.fadeOut(500, function() {
        gameplayScreen.fadeIn(500);
        gameplayScreen.show();
    });
});

mapIcon[1].click(function(){
    var selectedMap = ($('<img src="img/' + maps[1].image + '">'));
    gameplayScreen.append(selectedMap);
    mapSelectScreen.fadeOut(500, function() {
        gameplayScreen.fadeIn(500);
        gameplayScreen.show();
    });
});

mapIcon[2].click(function(){
    var selectedMap = ($('<img src="img/' + maps[2].image + '">'));
    gameplayScreen.append(selectedMap);
    mapSelectScreen.fadeOut(500, function() {
        gameplayScreen.fadeIn(500);
        gameplayScreen.show();
    });
});

gameplayScreen.click(function() {
    gameplayScreen.fadeOut(500, function() {
        mapSelectScreen.fadeIn(500);
        mapSelectScreen.show();
        gameplayScreen.empty();
    });
});

我想单击 map ,然后将其带到游戏屏幕,然后再次单击以像这些功能一样将我带回去。

我认为这与使用for循环有关,并通过单击“a mapIcon[i].click(function(){/*foo*/})”对其进行迭代,但是我无法使其正常工作。

我想这不喜欢为.click设置数组元素。有任何想法吗?这是目前对多功能的一种尝试。
for (i=0; i< mapIcon.length; i++){
    mapIcon[i].click(function(){
    var selectedMap = ($('<img src="img/' + mapIcon[i].image + '">'));
            gameplayScreen.append(selectedMap);
            mapSelectScreen.fadeOut(500, function() {
                gameplayScreen.fadeIn(500);
                gameplayScreen.show();
                console.log(mapIcon[i].name);
            });
        });
}

最佳答案

尝试

for (i=0; i< mapIcon.length; i++){
    (function(){
      var item = mapIcon[i];
      item.click(function(){
            var selectedMap = ($('<img src="img/' + item.image + '">'));
            gameplayScreen.append(selectedMap);
            mapSelectScreen.fadeOut(500, function() {
                gameplayScreen.fadeIn(500);
                gameplayScreen.show();
                console.log(item.name);
            });
        });
    })();
}

它应该清除scope issues

09-25 17:57