我正在尝试使用数组中的数据动态创建一个选择框,我尝试观看一些 JSON 教程,但仍然遇到一些问题。
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);
});
如您所见,代码未完全运行,因为它没有正确编写。如何从第二部分获取值(value)数据和从第一部分获取选项文本?基本上 html 应该是这样的
<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>
感谢任何解释或建议。只是希望这段代码能够工作,因为我只是在为自己的类(class)编写这些代码
最佳答案
您可以将数组更改为 JSON 对象..
var clothes = {
"Red Dress":"reddress.png",
"Blue Dress":"bluedress.png",
"Black Hair Pin":"hairpin.png"
};
然后迭代变得更容易..
for(var item in clothes)
{
$('<option value="'+item+'">'+clothes[item]+'</option>').appendTo('#clothing_options');
}
这是 HTML:
<div id="select_box_wrapper">
<select id="clothing_options"></select>
</div>
关于javascript - 使用数组中的数据动态创建选择框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16410058/