JavaScript - 如何获取外部onload函数中定义的变量?

Mas*_*gol 3 javascript

我想在html页面中获取所有输入元素.我试过这个:

window.onload = function(){
    input = document.querySelectorAll("input");
}
Run Code Online (Sandbox Code Playgroud)

但是,当我在外面用警报功能检查它时onload,它什么也没做

alert(input.length) // doesn't do anything
Run Code Online (Sandbox Code Playgroud)

如果我使用它,这将给我html页面中输入元素的数量.

window.onload = function(){
    input = document.querySelectorAll("input");
    alert(input.length);
}
Run Code Online (Sandbox Code Playgroud)

这意味着我无法在外面访问它.我怎样才能在外面访问它?

UPDATE

这就是html页面的样子:

<html>
<head>
    <script type="text/javascript" src="actions.js"></script>
</head>
<body>
    <label for="name">Name:</label><br/>
    <input type="text" id="name" /><br/>
    <label for="address">Address:</label><br/>
    <input type="text" id="address" /><br/>
    <label for="email">E-mail:</label><br/>
    <input type="text" id="email" />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Mad*_*iha 5

有几种方法可以做到这一点.

危险的方式

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

这假设Sometime later...window.onload被解雇之后神奇地发生,这可能是也可能不是,你无法保证.

Hacky Way

您可以确保<script>在页面底部找到所有元素.这消除了需要window.onload,但正如我所说,它是hacky.包含顺序无关紧要.

承诺的方式

使用ES6(或像蓝鸟这样的库),你有Promise!所以你可以这样做:

/**
 * 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以打电话给...

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.
Run Code Online (Sandbox Code Playgroud)

而在其他地方......

// 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);
});
Run Code Online (Sandbox Code Playgroud)