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

前端 未结 2 1032
忘掉有多难
忘掉有多难 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);
    

提交回复
热议问题