如何将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

09-18 22:57