javascript - 如何从填充有 JSON 数据的下拉列表中获取选择的详细信息?

标签 javascript jquery html json

我有以下test.json:

{"countries":[{"countryCode":"US","officialName":"UNITED STATES OF AMERICA","continent":"NORTH AMERICA","currentSeason":"WINTER"},{"countryCode":"AR","officialName":"ARGENTINA","continent":"SOUTH AMERICA","currentSeason":"SUMMER"}]}

下面的 html/jQuery 使用 JSON 数据中的 officialName 值填充下拉列表:

<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">
    <script src="jquery.js"></script>
</head>
<body>
    <div>
       <select id="countries"></select>
       <br>
       <textarea id="detailsbox" rows="4" cols="50">
       </textarea>
    </div>
</body>
<script type="text/JavaScript">
    $(document).ready(function() {
        var $select = $('#countries')
        $.getJSON('test.json',function(translations){
        $select.html('');
        //iterate over the data and append a select option
        $.each(translations.countries, function(key, val){ 
        $select.append('<option id="' + val.countryCode + '">' + val.officialName + '</option>');
       })
    });
    });
</script>
</html>

我的问题是,如何根据所选国家/地区访问其他相关数据(例如 currentSeason、countryCode、Continental),并使用该数据填写 detailsBox 文本区域?

谢谢。

最佳答案

var translations = {
  "countries": [{
    "countryCode": "US",
    "officialName": "UNITED STATES OF AMERICA",
    "continent": "NORTH AMERICA",
    "currentSeason": "WINTER"
  }, {
    "countryCode": "AR",
    "officialName": "ARGENTINA",
    "continent": "SOUTH AMERICA",
    "currentSeason": "SUMMER"
  }]
}

var $select = $('#countries')
$.each(translations.countries, function(key, val) {
  $select.append('<option id="' + val.countryCode + '">' + val.officialName + '</option>');
})

$select.change(function() {
  var countrycode = $("option:selected",this).attr('id');

  $.each(translations.countries, function(key, val) {
    console.log(val.countryCode)
    console.log(countrycode)
    if(val.countryCode == countrycode)
    $("#detailsbox").text("season is " +val.currentSeason)
  })


}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <select id="countries"></select>
  <br>
  <textarea id="detailsbox" rows="4" cols="50">
  </textarea>
</div>

  1. 使用更改事件
  2. 加载时选择的火灾变化事件

关于javascript - 如何从填充有 JSON 数据的下拉列表中获取选择的详细信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42151288/

相关文章:

jquery - 使用 Jquery 的简单站点地图

javascript - 如何让我的箭头文本留在 fullpage.js 上的正确位置?

html - 内联 block 不会以某种方式显示在一条直线上

javascript - xsl 生成 html 表,每行都有一个按钮

html - CSS 动画序列

javascript - Pino 格式化程序和序列化程序之间的差异

javascript - Uncaught Error : Minified React error #200

javascript - React Native 从 StackNavigator 导航到另一个 StackNavigator 或 TabNavigator

javascript - 以 O(log n) 的顺序查找已排序数组中元素的第一个和最后一个位置

javascript - 通过浏览器对网页进行身份验证