JavaScript - 全局变量不递增

时间:2018-02-03 21:38:05

标签: javascript function variables global-variables

我的程序使用数组跟踪车辆对象。我有一个变量跟踪我所显示的当前汽车的索引位置,名为 nIndex 。按下按钮,我调用 nextIMG 功能,该功能尝试增加索引,然后显示下一辆车。但是,执行console.log会显示它没有递增。如果我在浏览器中手动设置它并调用nextIMG它可以工作。

我真的很困惑,为什么这不应该工作,任何帮助将不胜感激谢谢。

var yearID = document.getElementById("year");
var makeID = document.getElementById("make");
var modelID = document.getElementById("model");
var priceID = document.getElementById("price");
var imgID = document.getElementById("picture");

var aVehicles = [];
var nIndex = 0;

addToArray(aVehicles, new Vehicle(2010, "Chevrolet", "Aveo", 6050, "media/aveo.png"));
addToArray(aVehicles, new Vehicle(2012, "Dodge", "Ram", 14398, "media/ram.png"));
addToArray(aVehicles, new Vehicle(2016, "Volvo", "VLN64T 780", 99950, "media/VNL64T780.jpg"));

aVehicles[0].showInfo(yearID, makeID, modelID, priceID, imgID);


//Event Handlers
document.getElementById("btnNext").addEventListener("click", nextIMG);
document.getElementById("btnNext").addEventListener("click", previousIMG);


function Vehicle(year, make, model, price, imagesrc)
{
    this.year = year;
    this.make = make;
    this.model = model;
    this.price = price;
    this.imagesrc = imagesrc;
    this.summarize = function (){
        return this.year + " " + this.make + " " + this.model;
    }
    this.showInfo = function (yearID, makeID, modelID, priceID, imgID) {
        yearID.innerHTML = this.year;
        makeID.innerHTML = this.make;
        modelID.innerHTML = this.model;
        priceID.innerHTML = this.price;
        imgID.src = this.imagesrc;
        imgID.alt = this.summarize();
    }
}

function addToArray(array, object)
{
    array[array.length] = object;
}

function nextIMG() {
    console.log(nIndex);
    nIndex = nIndex + 1;
    console.log(nIndex);
    aVehicles[nIndex].showInfo(yearID, makeID, modelID, priceID, imgID);
    console.log(nIndex);
}

function previousIMG() {
    if (nIndex === 0)
    {
        nIndex = aVehicles.length - 1;
    }
    else
    {
        nIndex--;
    }
    aVehicles[nIndex].showInfo(yearID, makeID, modelID, priceID, imgID);
}

1 个答案:

答案 0 :(得分:0)

您已将侦听器调用next和previous函数添加到同一按钮。把第二个放在btnPrev上。

  //Event Handlers
document.getElementById("btnNext").addEventListener("click", nextIMG);
document.getElementById("btnPrev").addEventListener("click", previousIMG);