2017-10-09 74 views
1

我有一些数据在JSON格式,我想添加到我的选择。Javascript填充选择与JSON数据在ES6(不含jQuery)

下面是数据:

{ 
    "timezones": 
    { 
     "country": "Africa", 
     "tz": "Africa/Abidjan" 
    }, 
    { 
     "country": "America", 
     "tz": "America/Anguilla" 
    } 
} 

这是当前选择:

<select> 

    <optgroup label="Africa"> 
     <option value="Africa/Abidjan">Adak</option> 
    </optgroup> 

    <optgroup label="America"> 
     <option value="America/Adak">Anguilla</option> 
    </optgroup> 

</select> 

我如何填充选择从JSON数据,而不是硬而不jQuery的编码呢?

+0

您的对象抛出语法错误。 –

+0

'timeszones'应该是一个数组,或者每个条目都应该有一个索引。 – JoeriShoeby

+0

1.修正截至目前无效的数据/ JSON。 2.为什么''元素?会有多个条目吗? 3.'

回答

1

您可以使用appendChild方法结合.forEach方法。

let obj={ 
 
    "timezones": 
 
    [{ 
 
     "country": "Africa", 
 
     "tz": "Africa/Abidjan" 
 
    }, 
 
    { 
 
     "country": "America", 
 
     "tz": "America/Anguilla" 
 
    }] 
 
}; 
 
let select=document.getElementById('countrySelect'); 
 
obj.timezones.forEach(function(item){ 
 
    let newOptGroup=document.createElement('optgroup'); 
 
    newOptGroup.label=item.country; 
 
    let option=document.createElement('option'); 
 
    option.value=item.tz; 
 
    option.text=item.tz; 
 
    newOptGroup.appendChild(option); 
 
    select.appendChild(newOptGroup); 
 
});
<select id="countrySelect"> 
 

 
</select>

+0

文本与数值不同(并且根本没有包含在数据/问题中) – Andreas

+0

@Andreas,我知道,但我给OP解决方案如何创建他的选择元素,这是主要部分。 –

0

起初,你是JSON数据是无效的。 '时区'应该是一个数组,或者每个对象都有一个索引。

数据

let data = { 
    "timezones": [ 
    { 
     "country": "Africa", 
     "tz": "Africa/Abidjan" 
    }, 
    { 
     "country": "America", 
     "tz": "America/Anguilla" 
    }] 
} 

我会填充选项如下:

data.timeszones.forEach(function(timezone) { 
    let optionGroup = document.createElement('optgroup'); 
     optionGroup.setAttribute('label', timezone.country); 

    let option = document.createElement('option'); 
     option.setAttribute('value', timezone.tz); 

    optionGroup.appendChild(option); 
    document.getElementById('selectionList').appendChild(optionGroup); 
}); 

而且obvisously,不要忘了一个ID设置为你的元素。

<select id='selectionList'> 
    <optgroup label="Africa"> 
     <option value="Africa/Abidjan">Adak</option> 
    </optgroup> 

    <optgroup label="America"> 
     <option value="America/Adak">Anguilla</option> 
    </optgroup> 
</select>