如何使用对本地 JSON 文件的一个请求来填充多个下拉列表,使用 jQuery?

How to use one request to local JSON file to populate multiple dropdowns, using jQuery?

我试图在我的项目的多个地方使用 Country/City 下拉菜单,但是当我改变国家时,我遇到了一个不寻常的行为。如何发出一个请求来获取本地 JSON 文件并填充多个下拉列表? 这是我的代码:

$(document).ready(function() {
fetch('assets/test.json').then(response => {return response.json()}).then(selectData => {
  console.log(selectData)
  function updateSelectsBirth() {
      let citiesBirth = selectData[this.value].map((key, val) => {
        return $("<option />").text(key).val(key);
      });
      $("#cityBirth, #cityBirth1").empty().append(citiesBirth);
    }
    let stateBirth;
    $countryBirth = $("#countryBirth, #countryBirth1").on("change", updateSelectsBirth);        
    for (stateBirth in selectData) {
      $("<option />").text(stateBirth).val(stateBirth).appendTo($countryBirth);
    }
    $countryBirth.change();
  })  
});

还有 HTML

<select id="countryBirth"></select>
<select id="cityBirth"></select>
<br/>
<select id="countryBirth1"></select>
<select id="cityBirth1"></select>

这里还有一个 link 演示项目:link to the demo

意外行为来自

$("#cityBirth, #cityBirth1").empty().append(citiesBirth);

因为,当它更新城市时,它会更新所有下拉菜单,而不仅仅是一个。

所以你可以试试:

$(document).ready(function() {
fetch('assets/test.json').then(response => {return response.json()}).then(selectData => {
  // console.log(selectData)
  function updateSelectsBirth(event) {
      let citiesBirth = selectData[this.value].map((key, val) => {
        return $("<option />").text(key).val(key);
      });
      // console.log(event.data.target)
      $(event.data.target).empty().append(citiesBirth);
    }
    let stateBirth;
    $countryBirth = $("#countryBirth").on("change", {target: "#cityBirth"}, updateSelectsBirth);   
    $countryBirth1 = $("#countryBirth1").on("change", {target: "#cityBirth1"}, updateSelectsBirth);   
    // $countryBirth1 = $("#countryBirth1").on("change", updateSelectsBirth("#cityBirth1"));        
    for (stateBirth in selectData) {
      $("<option />").text(stateBirth).val(stateBirth).appendTo($countryBirth);
      $("<option />").text(stateBirth).val(stateBirth).appendTo($countryBirth1);
    }
    $countryBirth.change();
    $countryBirth1.change();
  })  
});

抱歉,这不是一个完整的答案,因为我没有概括为多个下拉菜单,但是我还不能发表评论。我希望这仍然能有所帮助。