使用jQuery填充Select选项并设置默认值时默认项显示空白问题排查
问题原因及解决方案
问题原因
你在创建选中状态的<option>元素时,错误地将selected属性直接写在了标签字符串(<option selected>)中,这种写法和jQuery的属性配置对象结合时,会导致选项的文本内容无法正确渲染。虽然代码逻辑上已经选中了目标选项,但文本没有被正确绑定到DOM元素上,所以显示为空白。
修复代码
const sortedData = result.data.sort(); for (var i = 0; i < sortedData.length; i++) { const isSelected = sortedData[i] === userCountry; $("#country-selector").append( $("<option>", { value: sortedData[i], text: sortedData[i], selected: isSelected // 将selected状态统一放在属性配置对象中 }) ); }
额外优化建议
可以用数组映射结合jQuery批量添加选项,减少DOM操作次数,让代码更简洁:
const sortedData = result.data.sort(); const options = sortedData.map(country => $("<option>", { value: country, text: country, selected: country === userCountry }) ); $("#country-selector").append(options);
内容的提问来源于stack exchange,提问作者NicolaHearn
相关产品推荐
相关产品推荐

