【问题标题】:Creating a select box dynamically with data from array使用数组中的数据动态创建选择框
【发布时间】:2013-04-30 21:01:44
【问题描述】:

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

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

【问题讨论】:

    标签: javascript jquery arrays json for-loop


    【解决方案1】:

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

    【讨论】:

    • 感谢您的解释。现在对于 for(var item in Closs) 行,item 可以是任何东西吗?
    • 是的,var 'item' 可以被称为任何东西。它表示 json 对象中的每一项。
    【解决方案2】:

    第一个问题:

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

    这样就解决了。

    【讨论】:

    • 感谢您对这一切的解释
    猜你喜欢
    • 1970-01-01
    • 2019-07-01
    • 2021-07-07
    • 1970-01-01
    • 2011-08-08
    • 2019-06-28
    • 2019-01-26
    • 2020-06-11
    • 1970-01-01
    相关资源
    最近更新 更多