为我的孩子制作一个数学游戏;如何根据他们的选择切换图像?

Making a math game for my kids; how do I switch images based on their selection?

我正在为我的孩子制作一个简单的小数学抽认卡游戏。他们玩游戏的部分吸引力在于他们能够 "choose" 一个电子游戏角色,当问题对或错时,该角色会动画。

目前,我的抽认卡和代码工作正常。我在 /images 文件夹中为不同的场景保存了一些视频游戏角色的动画 GIF。

我的孩子表面上会从 select 元素中选择他们的角色,然后开始游戏并观看魔法发生。

我不是专业的程序员,但似乎应该有一种更优雅的方法来根据 select 调用合适的 GIF 集。而不是为他们可以选择的 10 个不同字符编写一堆 if/else 条件。

有没有办法将各种 GIF 的 src 路径放在一个数组中,或者 object 只能为特定字符调用?有人可以帮我提点想法吗?

我在想:

var chars = {
char1_right: "/path/to/this GIF",
char1_wrong: "/path/to/this GIF",
char2 etc...
}

然后

var img = new Image();
var img.src = chars.??? // changed based on the select box selection

更新的解决方案: 根据@runco​​m 的建议, 我这样设置了一个object:

var img_map = {
    ken: {
        win: 'http://www.zweifuss.ca/colorswap.php?pcolorstring=KenPalette.bin&pcolornum=0&pname=ken/ken-fireball.gif',
        lose: 'http://www.zweifuss.ca/colorswap.php?pcolorstring=KenPalette.bin&pcolornum=0&pname=ken/ken-twist.gif'
    },
    ryu: {
        win: 'http://www.zweifuss.ca/colorswap.php?pcolorstring=RyuPalette.bin&pcolornum=0&pname=ryu/ryu-shoryuken.gif',
        lose: 'http://www.zweifuss.ca/colorswap.php?pcolorstring=RyuPalette.bin&pcolornum=0&pname=ryu/ryu-twist.gif'
    },
    dhal: {
        win: 'http://www.zweifuss.ca/colorswap.php?pcolorstring=OroPalette.bin&pcolornum=0&pname=oro/oro-uppercut.gif',
        lose: 'http://www.zweifuss.ca/colorswap.php?pcolorstring=OroPalette.bin&pcolornum=0&pname=oro/oro-twist.gif'
    }

};

并更新了 img.src 属性:

var img_win = new Image();
var img_lose = new Image();
img_win.src = img_map.ken.win;
img_lose.src = img_map.ken.lose;
$('#charac').on('change', function () {
    var sel = $(this).val();
    if (sel in img_map) {
        img_win.src = img_map[sel].win;
        img_lose.src = img_map[sel].lose;
    }

});

示例如下 fiddle:http://jsfiddle.net/z17LgyLn/1/

您可以为 holding/storing 图像路径创建一个 Map(从技术上讲是一个 Object),然后对其进行操作以获取正确的 src,

var mapOfSource = {};
mapOfSource['key1'] = 'src1';
mapOfSource['key2'] = 'src2';

并且,在 select 的更改事件中,您可以通过简单地使用

从地图中获取数据
 img.src=mapOfSource['key1']

对于其他备选方案,请参阅此 Q/A