
使用 jQuery 动态生成 元素时,若通过字符串方式传入 selected 属性(如 ""),会导致浏览器解析异常,使对应选项文本显示为空;应统一通过属性对象参数设置 selected: true/false。
使用 jquery 动态生成 `
在 jQuery 中动态构建
$("#country-selector").append(
$("<option selected>", {
value: "United Kingdom",
text: "United Kingdom"
})
);</option>
⚠️ 问题根源在于:$("
✅ 正确做法是完全通过属性对象声明所有特性,包括 selected 状态:
jQuery 1.12.4是jQuery 1.x系列的最后一个正式稳定版本,由jQuery团队于2016年发布。该版本主要面向需要兼容旧版浏览器环境的网站和Web应用,尤其适用于仍需支持Internet Explorer 6、Internet Explorer 7、Internet Explorer 8等老旧浏览器的项目。
const sortedData = result.data.sort();
for (let i = 0; i ", {
value: sortedData[i],
text: sortedData[i],
selected: isSelected // ✅ 布尔值:true 或 false
})
);
}
? 提示:selected: true 等价于原生 DOM 的 option.selected = true,语义清晰且跨浏览器稳定;避免使用 selected: "selected" 或字符串形式,因 jQuery 会将其视为属性名而非布尔状态。
此外,还可进一步优化为函数式写法,提升可读性与性能(减少重复 DOM 操作):
const options = result.data
.sort()
.map(country =>
$("<option>", {
value: country,
text: country,
selected: country === userCountry
})[0] // 转为原生 DOM 元素便于批量追加
);
$("#country-selector").empty().append(options);</option>
? 总结:
- 始终使用属性对象(而非 HTML 字符串)初始化 jQuery 元素,确保所有属性(含 selected、disabled 等布尔属性)行为一致;
- selected 必须赋布尔值 true/false,不可用字符串 "selected" 或空字符串;
- 推荐先构建完整选项集合再一次性 append(),避免频繁重排(reflow),提升渲染性能。










