首页 > 解决方案 > 为什么我的 js 在导航到视图之前会导致数组的最后一个图像出现?

问题描述

到目前为止,我的代码在单击它时成功地从一个图像转到另一个图像。

但是,我面临的问题是,一旦您到达最后一张图片并单击(将用户重定向到indexTwo.html),它会将用户带回到第一张图片大约 2 秒钟,然后重定向到indexTwo.html.

我的问题是:我将如何防止这种行为发生?换句话说:点击所有图片,点击最后一张图片后,将用户重定向到indexTwo.html根本看不到第一张图片。

注意:我知道if (imageId === 0) {...}语句是罪魁祸首,但不确定如何修复它。

let theImage = document.getElementById('the-image');

let index = [
    "http://tech21info.com/admin/wp-content/uploads/2013/03/chrome-logo-200x200.png",
    "https://cdn.tutsplus.com/net/uploads/legacy/155_drupal/200x200.png",
    "https://townandcountryremovals.com/wp-content/uploads/2013/10/firefox-logo-200x200.png"
];

let op = 1;
let imageId = 0;

let clickedImage = () => {
    // start animation opacity
    if(op === 1) {
        let timer = setInterval(() => {
            if(op <= 0.1) {
                // load the next image
                imageId = (1 + imageId) % index.length;
                theImage.src = index[imageId];

                // reset the opacity
                theImage.style.opacity = op = 1;
                clearInterval(timer);

                if (imageId === 0) {
                    window.location = "indexTwo.html";
                }

            } else {
                op -= 0.1;
                theImage.style.opacity = op;
            }
        }, 50)
    }
};

标签: javascriptdebugging

解决方案


您是否需要验证 imageId 和数字 0 的数据类型匹配?如果没有,请尝试使用 == 而不是 ===


推荐阅读