如何将此 json 填充到选择标记中
var data = {
"266": "Andy Employee II",
"26": "Annette Oliveira",
"214": "Edwina Umeyor",
"39": "Eva Britton",
"193": "Leigh Otterson",
"68": "Louise Edelston",
"71": "Margaret Williams",
"97": "Simon Harris"
};
最佳答案
有很多方法可以做到这一点:您可以构建 HTML 字符串并将其填充到 DOM 中,您可以创建 select
标记并附加 option
对其进行一一标记,或者您可以使用众多客户端框架之一,其中大多数都可以通过模板来实现此目的。
只是为了好玩,以下是如何在纯 JS 中实现此操作,无需框架:
var data = {
"266": "Andy Employee II",
"26": "Annette Oliveira",
"214": "Edwina Umeyor",
"39": "Eva Britton",
"193": "Leigh Otterson",
"68": "Louise Edelston",
"71": "Margaret Williams",
"97": "Simon Harris"
};
// Grab a reference to the element to which
// which we want to append the select tag, in
// this case the body.
var body = document.getElementsByTagName('body')[0];
// Create the select tag
var select = document.createElement('select');
var key, option, text;
// Loop over our data, creating an option tag
// for each and appending it to the select tag.
for (key in data) {
option = document.createElement('option');
option.value = key;
text = document.createTextNode(data[key]);
option.appendChild(text);
select.appendChild(option);
}
// Insert the select tag into the DOM.
body.appendChild(select);
关于javascript - 将json加载到选择标签+js中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14859695/