首页 > 解决方案 > 如何使用 jQuery 在两个链接的、填充有 JSON 下拉列表的选项中预先选择一个选项?

问题描述

我有两个经典的连锁国家和城市下拉列表。它们填充了 JSON,但我遇到了 2 个问题。第一个是:如何将默认的选择选项分别设置为“选择国家”和“选择城市”而不会出错。

第二个是:如何在下拉列表填充JSON预先选择某个选项?

PS 如果有人有纯 JavaScript 的解决方案,我也会很高兴。

$(document).ready(function() {
    
  let countriesCitiesURL = "https://api.npoint.io/0114d901f1e3dbd47abe";
  
  $.getJSON(countriesCitiesURL, (selectData) => {        
        function updateSelects(event) {
            let cities = selectData[this.value].map((key, val) => {
                return $("<option />").text(key).val(key);
            });            
            $(event.data.target).empty().append(cities); 
        }
        let stateBirth;
        
        for (stateBirth in selectData) {        
            $('#country').append(`<option value="${stateBirth}">${stateBirth}</option>`);
        }
        
        $("#country").on("change", {target: "#city"}, updateSelects);
    
    /* This one is working */
    // if (4 > 3) {
    //  $("#country").val(selectedCountry);
    // }
        
        
    }).fail( () => { alert("Error!"); });
    
    let selectedCountry = "GERMANY";
    
    /* But I need to make this one work... */
    // if (4 > 3) {
        // $("#country").val(selectedCountry);
    // }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="country">
  <option>Please select a country</option>
</select>

<select id="city">
  <option>Please select a city</option>
</select>

标签: javascripthtmljqueryjson

解决方案


  1. 选择“选择国家”时会引发错误,因为城市下拉菜单找不到要显示的相应城市。没有名为“选择国家”的国家。要解决此问题,您需要检查是否选择了有效的国家/地区选项。您可以通过检查国家/地区选择的值来做到这一点。
  2. 要使用预选选项呈现下拉菜单,首先您需要告诉您要预选哪个选项。样本数据没有关于预选的信息。我们需要添加它。

我修改 API 响应如下。布尔指示预选选项。当然,True 是预先选择的。在此示例中,MANCHESTER 是 ENGLAND 的默认设置。HAMBURG 是德国的默认设置。

{
  "ENGLAND": {
    "LONDON": false,
    "MANCHESTER": true,
    "LIVERPOOL": false
  },
  "GERMANY": {
    "MUNICH": false,
    "BERLIN": false,
    "HAMBURG": true
  }
}

$(document).ready(function() {

  let countriesCitiesURL = "https://api.npoint.io/9de0952973958c474e90";

  $.getJSON(countriesCitiesURL, (selectData) => {
    function updateSelects(event) {
      let cityOptions;

      if (this.value) {
        // valid country is selected
        let cities = selectData[this.value];
        cityOptions = Object.keys(cities).map(function(key) {
          var opt = $("<option />").text(key).val(key);

          // pre-selection check
          if (this[key]) {
            // if true, render it as selected
            opt = opt.attr('selected', '');
          }
          return opt;
        }, cities);
      } else {
        // the placeholder is selected
        cityOptions = $('<option />').text('Please select a city');
      }

      $(event.data.target).empty().append(cityOptions);
    }
    let stateBirth;

    for (stateBirth in selectData) {
      $('#country').append(`<option value="${stateBirth}">${stateBirth}</option>`);
    }

    $("#country").on("change", {
      target: "#city"
    }, updateSelects);

    /* This one is working */
    // if (4 > 3) {
    //  $("#country").val(selectedCountry);
    // }


  }).fail(() => {
    alert("Error!");
  });

  let selectedCountry = "GERMANY";

  /* But I need to make this one work... */
  // if (4 > 3) {
  // $("#country").val(selectedCountry);
  // }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="country">
  <option value="">Please select a country</option>
</select>

<select id="city">
  <option>Please select a city</option>
</select>


推荐阅读