如何动态地将json数组元素显示到select标签中?

时间:2016-10-13 06:00:48

标签: javascript jquery html arrays json

我有一个像这样的格式的JSON数组

 "StoreName":["10001 Main ST","10002 Part1","10004 MyStore1","10005 M STR",        "10008 Centro","10009 MyStore 02","1001 G","1001 H","10010 Store main ROAD","10011 Central M Store","10012 En Department","10013 M Station","10014 Test Center","10015 SubStore1","10016 AA","10018 M part #","10019 Test A - 26032016","1002 B","1002 I","10020 Test Central B "]

我必须访问它的每个元素并将其显示为选择标记中的选项

<select id ="storeNm" name="name">
  <option>--Select--</option>
  <option>---Here store name list contents---</option>
  <option>---Here store name list contents---</option>
</select>

我是JSON的新手,必须使用javascript / jQuery,所以任何帮助/指导都将不胜感激。

1 个答案:

答案 0 :(得分:8)

使用Array#map方法迭代并生成元素。元素可以是generate using jQuery

&#13;
&#13;
var data = {
  "StoreName": ["10001 Main ST", "10002 Part1", "10004 MyStore1", "10005 M STR", "10008 Centro", "10009 MyStore 02", "1001 G", "1001 H", "10010 Store main ROAD", "10011 Central M Store", "10012 En Department", "10013 M Station", "10014 Test Center", "10015 SubStore1", "10016 AA", "10018 M part #", "10019 Test A - 26032016", "1002 B", "1002 I", "10020 Test Central B "]
};

// create select tag
$('<select/>', {
  // set id of the element
  id: 'storenm',
  // generate html content by iterating over array
  html: data.StoreName.map(function(v) {
      // generate option with value and text content
      return $('<option>', {
        text: v,
        value: v
      });
    })
    // append the generated tag to body
}).appendTo('body');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;