问题
I have an external js file which has a function that is meant to run AFTER the document body has loaded. This is what I have so far but it's not working as it should. Some help please.
External JS File
window.document.body.addEventListener('load', numOfSelects());
function numOfSelects()
{
var selects = document.getElementsByTagName('select');
alert(selects.length);
}
The HTML file that calls this script does have a few select fields. The alert works but it shows 0. And after the alert shows then the body can be seen loaded. Obviously this is not what I wanted. What am I doing wrong? Thanks guys.
I have also tried this:
Still didn't work. Here's my code:
Parent File
<html>
<head>
<title>File 1</title>
<script src='file1.js'></script>
</head>
<body>
<select id='dd1'><option>First</option><option>Second</option></select>
<select id='dd2'><option>First</option><option>Second</option></select>
</body>
</html>
JS FILE
alert('start');
window.document.body.addEventListener('load', function(){alert(document.getElementsByTagName('select').length)});
alert('stop');
only the first alert shows. I feel like I have made a really silly error somewhere.
回答1:
You simply want
window.addEventListener('load', numOfSelects);
回答2:
You want
window.document.body.addEventListener('load', numOfSelects);
By including the parentheses, you were actually calling the function and passing it's return (which was nothing) as the second argument of "addEventListener," rather than referencing the function
回答3:
try this:
window.onload = function ()
{
numOfSelects();
};
来源:https://stackoverflow.com/questions/17401571/external-js-with-onload-event