[英]I have an option form and I would like to show a different image from a JSON file for each element of the option tag i choose
so I created an option form and at the bottom of this I have a div where i want to show images taken from a JSON file based on which voice of the option form i select.所以我创建了一个选项表单,在这个底部我有一个 div,我想根据我选择的选项表单的声音显示从 JSON 文件中获取的图像。 To be more specific, I'll write some code down here:
更具体地说,我将在这里写一些代码:
HTML: HTML:
<select name="classes">
<option value="knight">Knight</option>
<option value="mage">Mage</option>
<option value="priest">Priest</option>
</select>
JS: JS:
const classes = [
{
id: 1,
class: "knight",
male: "../class-png/male-knight.png",
female:"../class-png/female-knight.png"
},
{
id:2,
class:"mage",
male:"../class-png/male-mage.png",
female:"../class-png/female-mage.png"
},
{
id: 3,
class: "priest",
male: "../class-png/male-priest.png",
female:"../class-png/female-priest.png",
}
];
So if i select the "knight" option, i want to show the two png of the knights inside a div below and so on for the mage.因此,如果我选择“骑士”选项,我想在下面的 div 中显示骑士的两个 png,依此类推,以供法师使用。 .
. .
.
I would to do this using the id of the JSON objects我会使用 JSON 对象的 id 来做到这一点
Your html will be like this你的 html 会是这样
<select class="classes" name="classes">
<option value="knight">Knight</option>
<option value="mage">Mage</option>
<option value="priest">Priest</option>
</select>
<div id="imageWrapper"></div>
Here is your jquery code based on your selected option value这是基于您选择的选项值的 jquery 代码
<script>
let selectedClass = "knight";
const classes = [
{
id: 1,
class: "knight",
male: "../class-png/male-knight.png",
female:"../class-png/female-knight.png"
},
{
id:2,
class:"mage",
male:"../class-png/male-mage.png",
female:"../class-png/female-mage.png"
},
{
id: 3,
class: "priest",
male: "../class-png/male-priest.png",
female:"../class-png/female-priest.png",
}
];
// To load Images for pre-selected option
addImage();
$(document).ready(() => {
$(".classes").change(() => {
$("#imageWrapper").empty();
selectedClass = $('.classes :selected').val();
// change image on option change
addImage();
})
})
function addImage (){
$.each(classes, function( index, value ) {
if(value.class == selectedClass){
$("#imageWrapper").prepend('<img id="image" src="'+value.male+'" /><img id="image" src="'+value.female+'" />')
}
});
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.