如何将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;
}
答案 0 :(得分:1)
addEventListener
将函数作为其第二个参数。您只需传递一个调用dispCar
的函数,如下所示:
for (var i = 0; i < car.length; i++) {
car[i].addEventListener("mouseover", function() {
dispCar(i);
});
}
由于Closures,您仍然可以从i
访问addEventListener
。
答案 1 :(得分:0)
尝试设置你的for循环:
for (var i = 0; i < car.length; i++) {
car[i].addEventListener("mouseover", 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;
}
}