【问题标题】:how to display json array elements dynamically into select tag?如何将json数组元素动态显示到select标签中?
【发布时间】:2017-02-22 03:03:30
【问题描述】:

我有一个像这样格式的 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 进行操作,因此我们将不胜感激任何帮助/指导。

【问题讨论】:

  • 使用 .each 循环遍历您的列表并使用 append 将所选内容插入到选择中\
  • 我该怎么做,你能举个例子吗? @guradio
  • 请参阅下面的答案,它涵盖了您的所有要求

标签: javascript jquery html arrays json


【解决方案1】:

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

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');
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 不错的答案。但我想,除了文本之外,为选项设置一个值会很好。
  • @ThomasJunk : 选项的附加值 :)
  • 我在脚本标签中使用了代码 sn-p,甚至给出了 jQuery 库的链接,但看不到数据列表中的选项@PranavCBalan
  • @ShreyaRawal :如果你想更新现有选择标签中的选项,然后像jsfiddle.net/pranavcbalan/w2ps6zn8/1 那样做......或者如果你想追加然后使用追加而不是od html
  • @ShreyaRawal : 虽然总是用document ready handler 包装你的代码
猜你喜欢
  • 1970-01-01
  • 2011-09-26
  • 2016-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 2018-04-06
  • 1970-01-01
相关资源
最近更新 更多