JavaScript - How to take variable that defined inside onload function outside?

前端 未结 2 1033
忘掉有多难
忘掉有多难 2021-01-14 03:31

I want to get all input element in html page. I\'ve tried this:

window.onload = function(){
    input = document.querySelectorAll(\"input\");
}
相关标签:
2条回答
  • 2021-01-14 03:41

    Reference your script tags at the bottom of the HTML page and not in the head. This will remove any ambiguity as to whether the page has been loaded.

    window.onload = function(){
        input = document.querySelectorAll("input");
        alert(input.length);
    }
    

    Now you should be able to extract the code from "window.load()" and get the expected results.

    input = document.querySelectorAll("input");
    alert(input.length);
    
    0 讨论(0)
  • 2021-01-14 03:44

    There are a couple ways of doing it.

    The Dangerous Way

    var input; // Input declared outside
    window.onload = function(){
        input = document.querySelectorAll("input");
    }
    // Sometime later...
    alert(input.length);
    

    This assumes that Sometime later... magically happens after window.onload was fired, which may or may not be the case, you have no guarantee.

    The Hacky Way

    You can make sure all of your <script> elements are found at the bottom of your page. This eliminates the need for window.onload, but as I said, it's hacky. Order of inclusion shouldn't matter.

    The Promised Way

    With ES6 (or with a library like bluebird), you have Promises! So you can do something like this:

    /**
     * Returns a promise the resolves when window fires the load event
     */
    function onload() {
        return new Promise(function(resolve, reject) {
            // Resolve if window is already loaded by the time this is called.
            if (document.readyState === 'complete') { return resolve(); }
            // If reached here, window not loaded. Resolve when it is.
            window.addEventListener('load', resolve);
        }
    }
    

    Then you can call...

    var inputAvailable = onload().then(function() {
        var input = document.querySelectorAll('input');
        return input;
    });
    // inputAvailable is a Promise object that resolves once querySelectorAll()
    // is executed and the result returned. It resolves with the returned value.
    

    And somewhere else...

    // The handler passed to .then will be called once inputAvailable resolves.
    // Which is always after querySelectorAll() was executed.
    inputAvailable.then(function(inputs) {
        alert(inputs.length);
    });
    
    0 讨论(0)
提交回复
热议问题