可能重复:
在 for 循环中分配点击处理程序
我对javascript有点天真。我有这个应该在按钮单击时运行的 javascript 代码。按钮是在循环中动态生成的。我所期望的是在每次单击按钮时都会收到不同的变量。但我收到的总是数组中的最后一个变量。请参阅下面的代码。有人在这里看到明显错误的地方吗?
<!doctype html>
<html>
<head>
<script type="text/javascript">
var myCars=["Saab","Volvo","BMW"];
function loadCars() {
var carList = document.getElementById('mydiv');
for(var i=0;i < myCars.length ; i++ ){
//Append button
var el = document.createElement("button");
var car = myCars[i];
el.name = "view_car";
el.id = "view_car";
el.value = "View car";
el.type = "button";
el.title = "View car "+i;
el.innerHTML = "View car "+car;
el.onclick = function() {
showMe(car,i);
};
carList.appendChild(el);
}
}
function showMe(carName,index){
alert("Selected car="+carName +" , index="+index);
}
</script>
</head>
<body onload="loadCars()">
Cars will be loaded here
<div id="mydiv" class="carlist"></div>
</body>
</html>