gpt4 book ai didi

JavaScript - 如何将定义在 onload 函数内部的变量移到外部?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:04:00 24 4
gpt4 key购买 nike

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

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

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

alert(input.length) // doesn't do anything

如果我使用它,它会给我 html 页面中输入元素的数量。

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

这意味着我不能从外面访问它。如何在外部访问它?

更新

这是 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>

最佳答案

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

危险之路

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

这假设Sometime later...神奇地发生在 window.onload 之后是否被解雇,你无法保证。

黑客之路

您可以确保所有 <script>元素位于页面底部。这消除了对 window.onload 的需要,但正如我所说,它很老套。包含顺序无关紧要。

应许之路

有了 ES6(或类似 bluebird 的库),你就有了 Promises!所以你可以这样做:

/**
* 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);
}
}

然后你可以调用...

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.

还有别的地方...

// 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);
});

关于JavaScript - 如何将定义在 onload 函数内部的变量移到外部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28813201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com