比较sessionStorage值时,Javascript函数无法调用

Javascript function not being able to call when sessionStorage value is compared

本文关键字:调用 函数 Javascript sessionStorage 值时 比较      更新时间:2023-09-26

我目前正在创建一个flash库,每次按下新按钮查看新的flash时,我都希望看到页面重新加载以显示新的广告。我已经解决了console.log的问题,并确定sessionStorage变量设置正确,但当调用back/rand/next()函数时,它就会停止。任何提示都很有价值。

(编辑)它进入console.log("收到兰德按钮!");

代码

 var flashcon, test, temp;
    var back, rand, next;
    back = document.getElementById('back');
    rand = document.getElementById('rand');
    next = document.getElementById('next');
    flashcon = document.getElementById('flashcon');
    function init() {
        if (sessionStorage.getItem('ref') == 1) {
            console.log('Back button ses received!');
            back();
        } else if (sessionStorage.getItem('ref') == 2) {
            console.log('Rand button ses received!');
            rand();
        } else if (sessionStorage.getItem('ref') == 3) {
            console.log('Next button ses received!');
            next();
        } else {
            console.log('First time or a reset');
        }
        // Scripts for the buttons
        back.onclick = function () {
            console.log('Back button pressed');
            sessionStorage.setItem('ref', 1);
            location.reload();
        };
        rand.onclick = function () {
            console.log('Rand button pressed');
            sessionStorage.setItem('ref', 2);
            location.reload();
        };
        next.onclick = function () {
            console.log('Next button pressed');
            sessionStorage.setItem('ref', 3);
            location.reload();
        };
    }
    // What switches the flashs
    function back() {
        console.log('Back function');
        sessionStorage.clear();
        if (c == 0) {
            c = paths.length;
        }
        c--;
        displayFiles();
        download();
    }
    function rand() {
        console.log('Rand function');
        sessionStorage.clear();
        if (c == paths.length - 1) {
            c = -1;
        }
        c++;
        displayFiles();
        download();
    }
    function next() {
        console.log('Next function');
        sessionStorage.clear();
        temp = c;
        while (c == temp) {
            c = Math.floor(Math.random() * paths.length);
        }
        displayFiles();
        download();
    }

您拥有凌驾于彼此名称之上的变量和函数。

back, next, rand都是函数语句,它们被提升到对应变量名的... = document.getElementById('...')之上。

请更改函数名称或元素对象名称,然后重试。

所以基本上转向:

var back, rand, next;
back = document.getElementById('back');
rand = document.getElementById('rand');
next = document.getElementById('next');

进入这个:

var $back, $rand, $next;
$back = document.getElementById('back');
$rand = document.getElementById('rand');
$next = document.getElementById('next');

当然,还要编辑代码中后面的匹配位置,使它们指向正确的变量。