[英]JavaScript - How to take variable that defined inside onload function outside?
我想在html页面中获取所有输入元素。 我试过这个:
window.onload = function(){
input = document.querySelectorAll("input");
}
但是,当我在onload
之外用alert函数检查它时,它什么也没做
alert(input.length) // doesn't do anything
如果我使用它,这将给我html页面中输入元素的数量。
window.onload = function(){
input = document.querySelectorAll("input");
alert(input.length);
}
这意味着我无法在外面访问它。 我怎样才能在外面访问它?
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>
有几种方法可以做到这一点。
var input; // Input declared outside
window.onload = function(){
input = document.querySelectorAll("input");
}
// Sometime later...
alert(input.length);
这假设在Sometime later...
在window.onload
被触发后神奇地发生了,这可能是也可能不是,你无法保证。
您可以确保在页面底部找到所有<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);
}
}
然后你可以打电话给...
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);
});
在HTML页面的底部而不是在头部引用脚本标记。 这将消除页面是否已加载的任何歧义。
window.onload = function(){
input = document.querySelectorAll("input");
alert(input.length);
}
现在,您应该能够从“window.load()”中提取代码并获得预期的结果。
input = document.querySelectorAll("input");
alert(input.length);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.