从阵列数据动态地创建一个选择框 [英] Creating a select box dynamically with data from array
问题描述
我想创建动态数据一个选择框是一个数组中,我尝试观看一些JSON教程,但还是有一些麻烦。
i am trying to create a select box dynamically with data that is within an array, I tried watching some JSON tutorials, yet having some trouble still.
var clothes = [
Red Dress:"reddress.png",
Blue Dress:"bluedress.png",
Black Hair Pin:"hairpin.png"
];
var select = '<select id="clothing_options">';
for(var i=0;i<clothes.length;i++)
{
select +='<option value="'+secondPart[i]+'">'+firstPart[i]+'</option>';
}
$('#select_box_wrapper').append(select+'</select>');
$('#clothing_options').change(function() {
var image_src = $(this).val();
$('#clothing_image').attr('src','http://www.imagehosting.com/'+image_src);
});
你可以看到code未充分发挥作用,因为它是不正确写入。如何从第二部分和从第一部分中的选项的文本获得的值的数据?基本HTML应该是这样的。
as you can see code is not fully functioning because it is not written correctly. How do I get the data for value from the second part and the option text from the first part? basically html should look like this
<select id="clothing_options">
<option value="reddress.png">Red Dress</option>
<option value="bluedress.png">Blue Dress</option>
<option value="hairpin.png">Black Hair Pin</option>
</select>
感谢任何解释或建议。只是希望这个code的工作,因为我只是在做这些codeS教训为我自己
thanks for any explanations or suggestions. Just want this code to work, as I am just doing these codes for lessons for myself
推荐答案
您可以将您的阵列更改为JSON对象。
You could change your array to a JSON object..
var clothes = {
"Red Dress":"reddress.png",
"Blue Dress":"bluedress.png",
"Black Hair Pin":"hairpin.png"
};
然后迭代变得更加容易。
and then iteration becomes easier..
for(var item in clothes)
{
$('<option value="'+item+'">'+clothes[item]+'</option>').appendTo('#clothing_options');
}
这里是HTML:
Here's the HTML:
<div id="select_box_wrapper">
<select id="clothing_options"></select>
</div>
这篇关于从阵列数据动态地创建一个选择框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!