Javascript 使用数组中的数据动态创建选择框
我尝试用数组中的数据动态创建一个选择框,我尝试观看一些JSON教程,但仍然有一些问题Javascript 使用数组中的数据动态创建选择框,javascript,jquery,arrays,json,for-loop,Javascript,Jquery,Arrays,Json,For Loop,我尝试用数组中的数据动态创建一个选择框,我尝试观看一些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;
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);
});
正如您所看到的,代码没有完全正常运行,因为它没有正确编写。如何从第二部分获取值数据,从第一部分获取选项文本?基本上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>
谢谢你的解释和建议。我只是想让这段代码起作用,因为我只是在为自己的课程编写这些代码第一个问题:
var clothes = {
Red_Dress:"reddress.png",
Blue_Dress:"bluedress.png",
Black_Hair_Pin:"hairpin.png"
};
标识符中不能有空格
其次,要在对象中循环:
for (var key in clothes)
{
select +='<option value="'+clothes[key]+'">'+key+'</option>';
}
这将解决它。第一个问题:
var clothes = {
Red_Dress:"reddress.png",
Blue_Dress:"bluedress.png",
Black_Hair_Pin:"hairpin.png"
};
标识符中不能有空格
其次,要在对象中循环:
for (var key in clothes)
{
select +='<option value="'+clothes[key]+'">'+key+'</option>';
}
这会解决问题。您可以将数组更改为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>
您可以将数组更改为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>
谢谢你对这一切的解释谢谢你对这一切的解释谢谢你的解释。现在,对于衣服中的forvar item行,item可以是任何东西吗?是的,var‘item’可以称为任何东西。它代表json对象中的每一项。感谢您的解释。现在,对于衣服中的forvar item行,item可以是任何东西吗?是的,var‘item’可以称为任何东西。它表示json对象中的每个项。