javascript - 使用数组中的数据动态创建选择框

标签 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;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>

Demo

关于javascript - 使用数组中的数据动态创建选择框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16410058/

相关文章:

python - 加速嵌套 python 数组的操作

javascript - 在 Webkit 中读取 window.history.state 对象

javascript - Kendo AutoComplete + AngularJS + 对象数组

javascript - 如何根据背景图像的高度和宽度设置DIV尺寸

javascript - JQuery登录,按回车键登录

arrays - 将 ArrayList 转换为 JSONArray

javascript - 我的 XML 文件未通过 Google Chrome 和 Internet Explorer

javascript - 将宽度设置为最宽的元素,同时仍然有 float

javascript - 数组更新后的 knockout 绑定(bind)

php - 将 DirectoryIterator 转换为可映射数组?