如何将i
的值传输到函数dispCar()
我试图使用i
值表示的索引值从数组中选取对象。
var cars = document.getElementById("carList");
var car = cars.querySelectorAll("li");
for (var i = 0; i < car.length; i++) {
car[i].addEventListener("mouseover", dispCar);
}
function dispCar() {
var carStats = [
{Mfg: "Cadillac", Model: "CTS", Year: "2016", Horsepower: "600+hp", color: "White"},
{Mfg: "Buick", Model: "LaCrosse", Year: "2016", Horsepower: "310hp", color: "Champagn Silver Metalic"},
{Mfg: "Chevrolet", Model: "Camaro", Year: "2016", Horsepower: "475hp", color: "White"}
]
document.getElementById("display").className = "display";
document.getElementById("display").innerHTML = carStats[0].Mfg;
}
最佳答案
addEventListener
将函数作为第二个参数。您可以像这样传递一个调用dispCar
的函数:
for (var i = 0; i < car.length; i++) {
car[i].addEventListener("mouseover", function() {
dispCar(i);
});
}
由于Closures,您仍然可以从
i
访问addEventListener
。请参见
EventTarget.addEventListener
Documentation on MDN。