我正在从Json数组中获取数据并将其解析到一个下拉列表中,我设法将整个数组都放入了该下拉列表中,但是我试图仅显示城市名称,而不是名称和描述,如果我删除城市[i] [“说明”,则该下拉菜单将不起作用,这是我的代码:
<body>
<select id="sel" onchange="show(this)">
<option value="">-- Select --</option>
</select>
<div style="background-color:lightgray;color:white;margin-top:20px;">
<p id="msg"></p>
</div>
</body>
<script>
function populateSelect() {
// THE JSON ARRAY.
var cities = [{
"city": "London",
"description":"London, the capital of England and the United Kingdom, is a 21st-century city with history stretching back to Roman times. At its centre stand the imposing Houses of Parliament, the iconic ‘Big Ben’ clock tower and Westminster Abbey, site of British monarch coronations. Across the Thames River, the London Eye observation wheel provides panoramic views of the South Bank cultural complex, and the entire city."
},
{
"city": "New York",
"description": "New York City comprises 5 boroughs sitting where the Hudson River meets the Atlantic Ocean. At its core is Manhattan, a densely populated borough that’s among the world’s major commercial, financial and cultural centers. Its iconic sites include skyscrapers such as the Empire State Building and sprawling Central Park. Broadway theater is staged in neon-lit Times Square"
},
{
"city": "Rome",
"description":"Rome, Italy’s capital, is a sprawling, cosmopolitan city with nearly 3,000 years of globally influential art, architecture and culture on display. Ancient ruins such as the Forum and the Colosseum evoke the power of the former Roman Empire. Vatican City, headquarters of the Roman Catholic Church, has St. Peter’s Basilica and the Vatican Museums, which house masterpieces such as Michelangelo’s Sistine Chapel frescoes."
}];
var ele = document.getElementById('sel');
for (var i = 0; i < cities.length; i++) {
// POPULATE SELECT ELEMENT WITH JSON.
ele.innerHTML = ele.innerHTML +
'<option value="' + cities[i]['city'] + '">' + cities[i]['description'] + '</option>';
}
}
function show(ele) {
// GET THE SELECTED VALUE FROM <select> ELEMENT AND SHOW IT.
var msg = document.getElementById('msg');
msg.innerHTML = ' <b>' + ele.value + '</b>' + ' <b>' + ele.options[ele.selectedIndex].text + '</b> </br>' ;
}
populateSelect();
</script>
答案 0 :(得分:0)
我认为您可以做到:
'<option>' + cities[i]['city'] + '</option>';
如果这真的是您想要的,大声笑。