使用jQuery设置JSON样式

时间:2013-04-02 02:39:23

标签: javascript jquery json

我有一个JSON值,它有多个以逗号分隔的值。有没有办法让dom中的渲染作为选择下拉输入?

以下是我的标记的更详细视图。

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

2 个答案:

答案 0 :(得分:2)

使用split()方法可以实现。 split(&#34;,&#34;)将为每个逗号分隔的实体提供一组单独的字符串。然后,您可以使用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

答案 1 :(得分:1)

一种方法是使用普通的Javascript方法.split()

您需要split值字符串,然后将逗号分隔的字符串转换为数组。然后,您需要遍历数组以进行select下拉列表。

你的JSON返回函数里面有这样的东西(不完全是这些变量名,只是一个向你展示这个想法的例子):

$('#SelectContainer').html('<select name="mySelect">');
var options = value.split(',');
for (counter=0; counter < options.length; counter++)
{
    $('#SelectContainer').append('<option value="' + options[counter] + '">' + options[counter] + '</option>');
}
$('#SelectContainer').append('</select>');
相关问题