如何在美国各州制作下拉列表,在展开时显示完整的州名,但在选择后显示州名缩写?
我正在考虑在变更中使用jQuery,但还没有得到线索。
HTML应该是这样的:
<select id="state" name="states">
<option selected disabled>State</option>
</select>
JS应该是这样的:
var usStates = [{ name: 'New York', abbr: 'NY'},
{ name: 'New Jersey', abbr: 'NJ'},
{ name: 'New Mexico', abbr: 'NM'}
];
var usStates_len = usStates.length;
for(var i = 0; i < usStates_len; i++){
var option = document.createElement("option");
option.text = usStates[i].abbr;
option.value = i;
var select = document.getElementById("state");
select.appendChild(option);
}
答案 0 :(得分:0)
你可以这样做:
var usStates = [{
name: 'New York',
abbr: 'NY'
}, {
name: 'New Jersey',
abbr: 'NJ'
}, {
name: 'New Mexico',
abbr: 'NM'
}];
$('#state').mousedown(function() {
if ($('#state option').length == 1) {
for (var i = 0; i < usStates.length; i++) {
$(this).append('<option value="' + usStates[i].abbr + '">' + usStates[i].name + '</option>')
}
} else {
for (var i = 0; i < usStates.length; i++) {
$('#state option').eq(i + 1).text(usStates[i].name)
}
}
}).change(function() {
$(this).find('option').each(function() {
$(this).text($(this).val())
})
console.log(this.value)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="state" name="states">
<option selected disabled>State</option>
</select>