简体   繁体   中英

setting the variable of js function from within htm

I am creating a simple function that warns the user when they are about to close out of a web page. I am using the window.onbeforeonload function is javascript. What I am doing is that, I set a variable to false because of the evil window.onbeforeonload function.

function funky() {
var submitFormOkay = false;
window.onbeforeunload = function () {
    if (submitFormOkay == false) {
        return "You are about to leave this order form. You will lose any information...";
    }
}
}

In my html, this is what I am doing

<input type="submit" id="submit_button" onclick="submitFormOkay = true;">

My question however is that I need a way to fire the function funky(). I know I could use an onclick but if I do what is going to set the value of submitFormOkay.

Any help would be appreciated.

Why not make submitFormOkay a parameter of the function funky , and just call it with the given parameter?

<input type="submit" id="submit_button" onclick="funky(true);">

And in the JS file:

function funky(submitFormOkay) {
     window.onbeforeunload = function () {
        if (submitFormOkay == false) {
           return "You are about to leave this order form. You will lose any information...";
        }
    }
}

Without changing your HTML, I'd do this instead:

window.onbeforeunload = (function(w) {
    w.submitFormOkay = false;
    return function() {
        if (!w.submitFormOkay) {
            return "You are about to leave this order form. You will lose any information...";
        }
    };
})(window);

​A problem with ngmiceli's solution is that window.onbeforeunload 's callback never gets defined until the user is okay to leave the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM