J*aScript Select Option 点击事件失效问题排查与解决方案

本文旨在解决 J*aScript 中动态创建的 `
在 J*aScript 中,动态创建
问题分析
上述代码尝试通过循环遍历所有
- 事件类型错误:
- 动态元素绑定时机: 在页面加载时,可能
解决方案
正确的做法是为
盘古大模型
华为云推出的一系列高性能人工智能大模型
207
查看详情
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
autos = [{
id: 1,
year: 2011,
model: 'FORD FIESTA CONNECTED 1.1L PFI3',
color: 'MAGNETIC',
ccm: 1100,
fuel: 'benzin',
performance: '55 kW / 74 LE',
gearbox: '5 FOK. MANUÁLIS'
},
{
id: 2,
year: 2006,
model: 'FORD ECOSPORT TITANIUM 1.0L 125 M6',
color: 'DESERT ISLAND BLUE',
ccm: 990,
fuel: 'benzin',
performance: '92 kW / 125 LE',
gearbox: '5 FOK. MANUÁLIS'
},
{
id: 3,
year: 2025,
model: 'FORD Focus Connected 5 ajtós 1.0 ',
color: 'Kék',
ccm: 990,
fuel: 'benzin',
performance: '91 kW / 123 LE',
gearbox: '6 FOK. MANUÁLIS'
},
{
id: 4,
year: 2025,
model: 'FORD PUMA',
color: 'Kék',
ccm: 1000,
fuel: 'benzin',
performance: '91 kW / 123 LE',
gearbox: '6 FOK. MANUÁLIS'
},
{
id: 5,
year: 2025,
model: 'FORD KUGA TITANIUM 1.5L ECOBOOST 150 M6',
color: 'SOLAR SILVER',
ccm: 1497,
fuel: 'benzin',
performance: '110 kW / 149 LE',
gearbox: '6 FOK. MANUÁLIS'
},
{
id: 6,
year: 2025,
model: 'FORD MONDEO Titanium 2.0 FHEV 187 LE',
color: 'Metal Blue',
ccm: 1999,
fuel: 'Hybrid',
performance: '110 kW / 147 LE',
gearbox: 'CVT AUTOMATA'
},
{
id: 7,
year: 2025,
model: 'FORD S-MAX TITANIUM 2.0L TDCI 150LE M6 FWD',
color: 'MAGNETIC',
ccm: 1997,
fuel: 'Dízel',
performance: '110 kW / 149 LE',
gearbox: '6 FOK. MANUÁLIS'
},
{
id: 8,
year: 2025,
model: 'FORD GALAXY TITANIUM 2.0TDCI 150LE M6 FWD',
color: 'MAGNETIC',
ccm: 1997,
fuel: 'Dízel',
performance: '110 kW / 149 LE',
gearbox: '6 FOK. MANUÁLIS'
},
]
//OPTIONS
var x = document.createElement("SELECT");
x.setAttribute("id", "mySelect");
document.body.appendChild(x);
for (i = 0; i < autos.length; i++) {
var z = document.createElement("option");
z.setAttribute("value", autos[i].model);
var t = document.createTextNode(autos[i].model);
z.appendChild(t);
document.getElementById("mySelect").appendChild(z);
}
// 使用 change 事件监听器
x.addEventListener("change",
function(event) {
alert(event.target.value); // 获取选中的值并弹出提示框
});
</script>
</body>
</html>代码解释:
- 使用 x.addEventListener("change", function(event) { ... }); 为
- 在事件处理函数中,event.target.value 获取当前选中的
- alert(event.target.value); 弹出包含选中值的提示框。
注意事项
- 确保在
- 可以使用 event.target.options[event.target.selectedIndex].text 获取选中
总结
通过为
以上就是J*aScript Select Option 点击事件失效问题排查与解决方案的详细内容,更多请关注其它相关文章!

function(event) {
alert(event.target.value); // 获取选中的值并弹出提示框
});
</script>
</body>
</html>