JavaScript - 全局变量不递增



我的程序使用数组跟踪车辆对象。我有一个变量来跟踪我正在显示的当前汽车的索引位置,称为 nIndex。按下按钮时,我调用下一个IMG函数,该函数尝试增加索引,然后显示下一辆车。但是,执行控制台.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);
}

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

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

相关内容

  • 没有找到相关文章

最新更新