我有以下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>
- 使用更改事件
- 加载时选择的火灾变化事件
关于javascript - 如何从填充有 JSON 数据的下拉列表中获取选择的详细信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42151288/