如何使用Javascript初始加载后检测网页是否正在重新加载?

时间:2018-08-10 06:17:32

标签: javascript html

所以我有一个新手问题:如何在初始加载后检测页面是否已重新加载?

我问这个问题是因为我有一个问题:当用户进入页面时,我的JavaScript代码可以正常工作。但是当用户在该页面上并重新加载页面时,代码将中断并停止工作。

我正在尝试找到一种方法,以便在页面重新加载时重新加载代码,或者编辑我的代码以解决问题。

这是代码。这是一个动态下拉列表,其中有一个父母和一个孩子:

“使用严格”;

/*
The dynamic drop-down does not work properly with safari on mac OS. It does disable child options but they remain visible.
 */

window.onload = function () {

    //parent function start here ...
    function parent_() {
        let p = document.getElementById('category_select'),
            c = p.options[p.selectedIndex].value;
        return c; // return parent options value
    }
    //child function start here ...
    function child_() {
        // create a list of all child options in the dropdown ...
        let c = document.getElementById('type_select');
        for (let l = 0; l < c.options.length; ++l) {

            // if parent options value === child option values it display all child options values that match the selected parent value
            if (c.options[l].value === parent_()) {
                c.options[l].style.display = 'block';
                c.options[l].disabled = false;

                // and disable all child options that dont match the selected parent value
            } else
            if (c.options[l].value !== parent_()) {
                c.options[l].style.display = 'none';
                c.options[l].disabled = true;
            }
        }
    }
    let l = document.location.pathname;
    if (l === "/get-started") {
        // on page load, disable child drop-down
        let p = document.getElementById('category_select'),
            c = document.getElementById('type_select'),
            p_ = p.options[p.selectedIndex].value;
        if (p_ === "") {
            c.disabled = true;
        }
        p.addEventListener("change", function () {
            let p = document.getElementById('category_select'),
                c = document.getElementById('type_select'),
                p_ = p.options[p.selectedIndex].value;
            if (p_ !== "") { //parent drop-down has a selected value ...
                //get first child with options value equal to parent's one
                c.value = p_;
                //disable the child drop-down
                c.disabled = false;
                child_();
            } else if (p_=== "") {
                c.value = p_;
                c.disabled = true;
            }
        })
    } else
        if (l !== "/get-started"){
            return null;
        }
};

1 个答案:

答案 0 :(得分:0)

  • 您需要一个变量来保存页面状态时的状态 毁了。

  • 因此,您可以尝试使用cookie或localStorage,甚至可以将状态作为参数添加到url。初始化页面时,读取localStorage(例如),如果状态存在,则读取这些变量以使您的下拉菜单生效。如果没有,请从最后一页和初始页获取状态。