我有一个充满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();
});
});
我想点击地图,然后让它带我进入gameplayScreen,然后再次点击,让我像这些功能那样带我回去。
我认为它与使用for循环并迭代它以获得点击a'la 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);
});
});
}
答案 0 :(得分:1)
尝试
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
答案 1 :(得分:0)
尝试单独定义处理程序,然后分配它:
$(document).ready(function () {
'use strict';
var i = 0,
switchMap = function switchMap(e) {
var selectedMap = $('<img />').attr({
'src': 'img/' + this.image,
'alt': this.name
});
gameplayScreen.append(selectedMap);
mapSelectScreen.fadeOut(500, function () {
gameplayScreen.fadeIn(500);
gameplayScreen.show();
});
};
for (i = 0; i < mapIcon.length; i += 1) {
mapIcon[i].click(switchMap);
}
gameplayScreen.click(function () {
gameplayScreen.fadeOut(500, function () {
mapSelectScreen.fadeIn(500);
mapSelectScreen.show();
gameplayScreen.empty();
});
});
});