代码之家  ›  专栏  ›  技术社区  ›  Werokk

包含JSON数据的下拉列表

  •  -2
  • Werokk  · 技术社区  · 6 年前

    我从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>
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   20 fps    6 年前

    我想你可以这样做:

    '<option>' + cities[i]['city'] + '</option>';
    

    如果这真的是你想要的,哈哈。