javascript - 使用 jQuery 设置 JSON 样式

标签 javascript jquery json

我有一个 JSON 值,其中包含多个用逗号分隔的值。有没有办法将其作为选择下拉输入在 dom 中呈现?

这是我的标记的更详细 View 。

HTML

 <h1>JSON Grid Edit</h1>

     <table cellpadding="0" cellspacing="0" border="0" class="dt display" id="json-table-edit" contenteditable="true" onKeyUp="editValue(this.id);">
      <thead>
        <tr>
          <th width="25%">Setting</th>
          <th width="75%">Value</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
      <tfoot>
        <tr>
          <th>Setting</th>
          <th>Value</th>
        </tr>
      </tfoot>
    </table>

JSON

     {
      "allconfig": {
         "card.inserted": {
         "value": "Inserted, Not Inserted",
     },
        "card.cisproc": {
        "value": "Processed",
      }
     }
    }

JQUERY

$.getJSON('json/ione-edit.json', function (data) {
 var newJson = [];
 var myJson = data;
 $.each(myJson.allconfig, function (key, value) {
     var rowArray = [];
     rowArray.push(key);
     $.each(myJson.allconfig[key], function (key1, value1) {
         rowArray.push(value1);
     });
     newJson.push(rowArray);
 });
 $('#json-table-edit').dataTable({
     "bJQueryUI": true,
     "bStateSave": true,
     "sPaginationType": "full_numbers",
     "bProcessing": true,
     "oLanguage": {
         "sLengthMenu": ' <select>' + '<option value="10" selected="selected">Filter</option>' + '<option value="10">10</option>' + '<option value="20">20</option>' + '<option value="30">30</option>' + '<option value="40">40</option>' + '<option value="50">50</option>' + '<option value="-1">All</option>' + '</select>'
     },
     "aaData": newJson
 });

最佳答案

这可以使用 split() 方法实现。 split(",") 将为每个逗号分隔的实体提供一个单独的字符串数组。然后,您可以使用 jQuery .each() 方法迭代该数组并将每个字符串附加到包含在 <option> 中的 DOM。标签。

像这样:

 var data = {
  "allconfig": {
     "card.inserted": {
     "value": "Inserted, Not Inserted",
 },
    "card.cisproc": {
    "value": "Processed",
  }
 }
}

var options = (data.allconfig["card.inserted"]["value"]).split(",");

$("body").append("<select id='select'></select>");
//I am appending this to the body, but you can change body to
// whatever element/class/id you want 


$(options).each(function() {
  $("#select").append("<option>"+this+"</option>");
});
//I have also given the select an id so this code can be used on pages that have multiple select elements

这是一个fiddle

关于javascript - 使用 jQuery 设置 JSON 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15755165/

相关文章:

json - 如何解码嵌套结构 JSON

javascript - JSON to Go结构

javascript - 即使机器人离线或获得更新也能保存用户数据

javascript - 为什么 gtag.js 加载 2 个脚本而不是 1 个?

javascript - 如何在 Google 图表库的横轴上使用 2 位数年份?

javascript - ThreeJS 更改不透明度时更新场景

php - jQuery 自动完成菜单正在阻塞服务器

javascript - jquery 默认上下文

javascript - 现有电子邮件检查(Django + Javascript/Ajax)

javascript - jquery 响应后打开 javascript 弹出窗口