You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 07:02:08