我想在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>
答案 0 :(得分:5)
有几种方法可以做到。
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);
});
答案 1 :(得分:0)
引用HTML页面底部的脚本标记,而不是头部。这将消除页面是否已加载的任何歧义。
window.onload = function(){
input = document.querySelectorAll("input");
alert(input.length);
}
现在您应该能够从“window.load()”中提取代码并获得预期的结果。
input = document.querySelectorAll("input");
alert(input.length);