1. 用selected属性默认增加选中项:
<select name="" id="">
<option value="1">主航线</option>
<option value="2" selected>备航线</option>
</select> -->
2. 根据后台返回值进行回显,设置选中项
(假设后台返回被选中的下拉框数据为optionType为2)
❤ 法一
参考:关于select下拉框的数据回显_月来better的博客-CSDN博客_select下拉框的数据回显
<select name="" id="" class="selectedList">
<option value="1">主航线</option>
<option value="2">备航线</option>
<option value="3">主航线1</option>
<option value="4">备航线2</option>
</select>
<script type="text/javascript">
let optionType = 4;
let allSelect = $(".selectedList > option");
// allSelect.each((index, item) => {
// if ($(item).val() == optionType) {
// $(item).prop("selected", true);
// }
// });
// 或:
// 获取所有的option的value值,然后与后台返回的值(要回显的值)进行对比
// 若值相同则将selected属性指向这个值
for (let i = 0; i < allSelect.length; i++) {
let item = allSelect[i].value;
if (optionType == item) {
$(".selectedList option[value='" + item + "']").attr(
"selected",
"selected"
);
}
}
❤ 法二
<select name="" id="" class="selectedList">
</select>
<script type="text/javascript">
let optionType = 2;
$(".selectedList").append(`
<option ${
optionType == 1 ? "selected='selected'" : ""
} value="1">主航线</option>
<option ${
optionType == 2 ? "selected='selected'" : ""
} value="2">备航线</option>
<option ${
optionType == 3 ? "selected='selected'" : ""
} value="3">主航线1</option>
<option ${
optionType == 4 ? "selected='selected'" : ""
} value="4">备航线2</option>
`);
</script>