1

我正在尝试使用数组中的数据动态创建一个选择框,我尝试观看一些 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);
 });

如您所见,代码没有完全正常运行,因为它没有正确编写。如何从第二部分获取值数据和从第一部分获取选项文本?基本上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>

感谢您的任何解释或建议。只是希望这段代码能够工作,因为我只是在为自己的课程编写这些代码

4

2 回答 2

3

您可以将数组更改为 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>

演示

于 2013-05-07T02:10:20.117 回答
1

第一个问题:

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>';
 }

当然,这具有在选择框中显示“Red_Dress”的不良影响。

var clothes = {
 "Red Dress":"reddress.png",
 "Blue Dress":"bluedress.png",
 "Black Hair Pin":"hairpin.png"
};

那将解决它。

于 2013-05-07T02:06:43.630 回答