我试图将下面json中的数据从美国代表和参议员拉到下拉菜单中...理想情况下按" Sen"和#34; Rep"然后按字母顺序排列。到目前为止,下面的代码正在努力让所有成员进入下拉列表,但不进行分组或按字母顺序排列。会喜欢任何想法,谢谢!
<script>
$.ajax({
url:'https://theunitedstates.io/congress-legislators/legislators-
current.json',
dataType: 'json',
type:'get',
cache:false,
success:function(data) {
$(data).each(function(index, value) {
$("#members").append("<option>" + value.terms[value.terms.length-
1].type + " " + value.name.first + " " + value.name.last + "</option>");
});
}
});
</script>
<form>
<select id="members" style="text-transform:uppercase;">
<option selected="selected">Select...</option>
</select>
</form>
答案 0 :(得分:1)
HTML
<optgroup>
元素会在<select>
元素中创建一组选项。
(https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup)
<select id="members" style="text-transform:uppercase;">
<optgroup id="senators" label="Senators"></optgroup>
<optgroup id="reps" label="US Reps"></optgroup>
</select>
sort()
方法对数组中的元素进行排序并返回数组。
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
所以,如果您想按姓氏排序,可以试试这个:
var reps = [];
var senators = [];
$.ajax({
url: 'https://theunitedstates.io/congress-legislators/legislators-current.json',
dataType: 'json',
type: 'get',
cache: false,
success: function (data) {
$(data).each(function (index, value) {
if (value.terms[value.terms.length - 1].type == 'sen') {
// add to senators
senators.push(value.name.last + ', ' + value.name.first);
} else {
// add to reps
reps.push(value.name.last + ', ' + value.name.first)
}
});
senators.sort();
reps.sort();
senators.forEach(function (val) {
$("#senators").append("<option>" + "SEN. " + " " + val + "</option>");
});
reps.forEach(function (val) {
$("#reps").append("<option>" + "REP. " + val + "</option>");
})
}
});
JSFiddle: (https://jsfiddle.net/eb1ayera/)