本文介绍了JavaScript-如何将onload函数内部定义的变量带到外部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取html页面中的所有输入元素.我已经尝试过了:

I want to get all input element in html page. I've tried this:

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

但是,当我使用 onload 之外的警报功能对其进行检查时,它什么也没做

But, when I check it with alert function outside onload, it doesn't do anything

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

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

If I use this, this will give me the numbers of input element in html page.

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

这意味着我无法在外部访问它.我如何在外面访问它?

And that's mean I can't access it outside. How can I access it outside?

更新

这是html页面的外观:

This is how the html page looks like:

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

这假定有时稍后... 会在 window.onload 被触发后神奇地发生,这种情况可能会也可能不会发生,您不能保证.

This assumes that Sometime later... magically happens after window.onload was fired, which may or may not be the case, you have no guarantee.

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

You can make sure all of your <script> elements are found at the bottom of your page. This eliminates the need for window.onload, but as I said, it's hacky. Order of inclusion shouldn't matter.

有了ES6(或者像 bluebird 这样的库),您就可以实现了!因此,您可以执行以下操作:

With ES6 (or with a library like bluebird), you have Promises! So you can do something like this:

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

然后您可以致电...

Then you can call...

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函数内部定义的变量带到外部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 04:36