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

前端 未结 2 1056
忘掉有多难
忘掉有多难 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: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

提交回复
热议问题