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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16410058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:33:07  来源:igfitidea点击:

Creating a select box dynamically with data from array

javascriptjqueryarraysjsonfor-loop

提问by EasyBB

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.

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

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

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

thanks for any explanations or suggestions. Just want this code to work, as I am just doing these codes for lessons for myself

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

回答by Zim

You could change your array to a JSON object..

您可以将数组更改为 JSON 对象。

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

Here's the HTML:

这是 HTML:

<div id="select_box_wrapper">
  <select id="clothing_options"></select>
</div>

Demo

演示

回答by EasyBB

First problem:

第一个问题:

var clothes = {
 Red_Dress:"reddress.png",
 Blue_Dress:"bluedress.png",
 Black_Hair_Pin:"hairpin.png"
};

You can't have spaces in identifiers.

标识符中不能有空格。

Second, to loop through an object:

其次,循环遍历一个对象:

 for (var key in clothes)
 {
     select +='<option value="'+clothes[key]+'">'+key+'</option>';
 }

Of course this has the undesired effect of showing 'Red_Dress' in the select box.

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

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

That will fix it.

那将修复它。