如何在下拉列表中生成此代码

时间:2016-06-22 07:23:14

标签: jquery

json数组:

 {
     name: 'Heritage Bank',
     id: '030'
 }, {
     name: 'Jaiz Bank',
     id: '23'
 }, {
     name: 'Keystone Bank',
     id: '02'
 }, {
     name: 'Mainstreet Bank',
     id: '01'
 }, {
     name: 'Skye Bank',
     id: '06'
 }, {
     name: 'Stanbic IBTC',
     id: '21'
 }, {
     name: 'Standard Chartered',
     id: '06'
 }, {
     name: 'Sterling Bank',
     id: '22'
 }, {
     name: 'Union Bank',
     id: '02'
 }, {
     name: 'UBA',
     id: '3'
 }, {
     name: 'Unity Bank',
     id: '15'
 }, {
     name: 'Wema Bank',
     id: '35'
 }, {
     name: 'Zenith Bank',
     id: '7'
 }, {
     name: 'GT Bank',
     id: '08'
 }];

javascript代码:

 var sel = document.getElementById('banks');
 var fragment = document.createDocumentFragment();
 banks.forEach(function(banks, index) {
     var opt = document.createElement('option');
     opt.innerHTML = banks;
     opt.value = banks;
     fragment.appendChild(opt);
 });
 sel.appendChild(fragment);

1 个答案:

答案 0 :(得分:0)

你去吧

var arr =[
{ name: 'Heritage Bank', id: '030' }, 
{ name: 'Jaiz Bank', id: '23' }, 
{ name: 'Keystone Bank', id: '02' }, 
{ name: 'Mainstreet Bank', id: '01' }, 
{ name: 'Skye Bank', id: '06' }, 
{ name: 'Stanbic IBTC', id: '21' }, 
{ name: 'Standard Chartered', id: '06' }, 
{ name: 'Sterling Bank', id: '22' }, 
{ name: 'Union Bank', id: '02' }, 
{ name: 'UBA', id: '3' }, 
{ name: 'Unity Bank', id: '15' }, 
{ name: 'Wema Bank', id: '35' }, 
{ name: 'Zenith Bank', id: '7' }, 
{ name: 'GT Bank', id: '08' }
];

$(document).ready(function(){
var ele = $("<select/>");
for(var i=0;i<arr.length;i++)
{
    ele.append($('<option>', {value:arr[i].id, text:arr[i].name}));

}
//ele.append('</select>');
$('#someid').append(ele); // Append wherever you want
});

<强> Demo Here