Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为我的孩子做一个数学游戏;如何根据图像的选择切换图像?_Javascript_Jquery_Image - Fatal编程技术网

Javascript 为我的孩子做一个数学游戏;如何根据图像的选择切换图像?

Javascript 为我的孩子做一个数学游戏;如何根据图像的选择切换图像?,javascript,jquery,image,Javascript,Jquery,Image,我正在为我的孩子们制作一个简单的数学卡片游戏。他们玩游戏的部分吸引力在于,他们能够选择一个视频游戏角色,当游戏玩家发现问题是对是错时,这个角色就会产生动画效果 目前,我的抽认卡和代码运行良好。我在/images文件夹中为一个视频游戏角色保存了一些不同场景的动画GIF 我的孩子们表面上会从一个选定的元素中选择他们的角色,然后开始游戏并观看魔术的发生 我不是一个专业的程序员,但似乎应该有一种更优雅的方式来根据select调用适当的gif集。而不是为他们可以选择的10个不同字符编写一组if/else条

我正在为我的孩子们制作一个简单的数学卡片游戏。他们玩游戏的部分吸引力在于,他们能够选择一个视频游戏角色,当游戏玩家发现问题是对是错时,这个角色就会产生动画效果

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

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

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

有没有办法将各种GIF的src路径放入只能为特定字符调用的数组或对象中?有人能帮我提一些想法吗

我的想法是:

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

更新的解决方案: 根据@runcom的建议, 我设置了一个对象:

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的示例:。

您可以创建一个映射,从技术上讲,它是一个用于保存/存储图像路径的对象,然后对其进行操作以获取正确的src

并且,在select的更改事件中,您只需使用

 img.src=mapOfSource['key1']

其他备选方案见此。

,并查看此Q/A以了解不同的方法:谢谢,我愚弄了这个想法,它对我有效。我正在用我所做的事情更新我的问题。谢谢
var mapOfSource = {};
mapOfSource['key1'] = 'src1';
mapOfSource['key2'] = 'src2';
 img.src=mapOfSource['key1']