json对象值,使用jquery选择下拉列表更新

时间:2017-11-23 15:50:24

标签: javascript jquery json

我有json值,如

<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" rel="stylesheet"/>
<h1>
  Text that is not supposed to animate 
  <span style="color:#4ceb90" class="animated pulse infinite animatespan">pulsing word</span>
  Text that is not supposed to animate
  <span style="color:#4ceb90" class="animated pulse infinite animatespan">pulsing word</span>
  Text that is not supposed to animate
  <span style="color:#4ceb90" class="animated pulse infinite animatespan">pulsing word.</span>
</h1>

以上json值将使用jquery输出更新选择下拉列表,如

var roles = { "roles":[
     {"role_id":2,"role_name":"admin"},
     {"role_id":4,"role_name":"QA"},
     {"role_id":3,"role_name":"TL"},
     {"role_id":5,"role_name":"user"},
     {"role_id":1,"role_name":"root"}
 ]}

我正在使用这种方法

 <option value="2">admin</option>
 <option value="4">QA</option>
 <option value="3">TL</option>
 <option value="5">user</option>
 <option value="1">root</option>

我得到像

这样的输出
   var dropDownField = roles;
   if(typeof(dropDownField) === "object" && Object.keys(dropDownField).length) {
        $.each(dropDownField, function(key, data){
            console.log(key+'  '+data);
        });
    }

请帮我解决一下

1 个答案:

答案 0 :(得分:0)

进一步@Rory McCrossan评论,答:你需要在async function a() { var v = await setTimeout(function() { console.log("1"); }, 3000); console.log("2"); } a(); 而不是eachdropDownField.roles。 B.您可以“收集”数组中每个项目的html,然后https://pymotw.com/2/select将其收集到dropDownField

select
var roles = {
  "roles": [{
      "role_id": 2,
      "role_name": "admin"
    },
    {
      "role_id": 4,
      "role_name": "QA"
    },
    {
      "role_id": 3,
      "role_name": "TL"
    },
    {
      "role_id": 5,
      "role_name": "user"
    },
    {
      "role_id": 1,
      "role_name": "root"
    }
  ]
}

var dropDownField = roles;
var html = '';
if (typeof(dropDownField) === "object" && Object.keys(dropDownField).length) {
  $.each(dropDownField.roles, function(key, data) {
    html += `<option value="${data.role_id}">${data.role_name}</option>`;
  });
}

$('select').html(html);