带有onLoad事件的外部JS [英] External JS with onLoad Event
问题描述
我有一个外部js文件,该文件具有可以在文档主体加载后运行的功能.到目前为止,这是我所拥有的,但无法正常工作.请帮忙.
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.
外部JS文件
window.document.body.addEventListener('load', numOfSelects());
function numOfSelects()
{
var selects = document.getElementsByTagName('select');
alert(selects.length);
}
调用此脚本的HTML文件确实具有一些选择字段.警报起作用,但显示为0.在警报显示之后,可以看到主体已加载.显然这不是我想要的.我究竟做错了什么?谢谢大家.
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.
我也尝试过这个:
还是没有用.这是我的代码:
Still didn't work. Here's my code:
父文件
<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文件
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.
推荐答案
您只是想要
window.addEventListener('load',numOfSelects);
window.addEventListener('load', numOfSelects);
这篇关于带有onLoad事件的外部JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!