簡體   English   中英

使用數組中的數據動態創建選擇框

[英]Creating a select box dynamically with data from array

我正在嘗試使用數組內的數據動態創建一個選擇框,我嘗試觀看一些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>

感謝您的任何解釋或建議。 只是希望這段代碼能夠正常工作,因為我只是為自己做這些代碼

您可以將數組更改為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>

演示

第一個問題:

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

這將解決它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM