如何将值从区域传输到另一个区域

时间:2016-03-18 03:54:50

标签: javascript arrays javascript-events

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

2 个答案:

答案 0 :(得分:1)

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

答案 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;
  }

}