javascript 标签触发器 - 页面上的代码位置
当标签显示
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
<iframe></iframe>
</body>
</html>
奇怪时,我使用该标签来提醒我,因为此代码可以工作:
<html>
<head>
</head>
<body>
<iframe></iframe>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
</body>
</html>
为什么 Js 需要在该标签下才能工作? 这里有什么问题吗?
i use that tag to alert me when a tag has been shows up
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
<iframe></iframe>
</body>
</html>
strange , since this code working :
<html>
<head>
</head>
<body>
<iframe></iframe>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
</body>
</html>
why the Js need to under the tag to work?
what's the problem here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为脚本标签中的代码是立即执行的。在第一个示例中,iframe 当时还不存在。但您可以做的是将代码包装到 onload(对于主页)事件中。例如:
那么代码放在哪里并不重要。
Because the code in a script tag is executed immediately. And in the first example the iframe doesn't exist at that time. But what you can do is to wrap you code into an onload (for the main page) event. E.g.:
Then it doesn't matter where the code is placed.
您尝试访问 iframe 标记时不存在。
您可以通过简单地警告数组长度来检查这一点,例如
您是否考虑过在页面加载后执行 JavaScript?您可以使用一些框架,例如 jQuery 来解决跨浏览器问题。或者只是将所有 javascript 代码放在正文的最底部。
Iframe tag does not exist at the moment you are trying to access it.
You may check that by simply alerting array length, like
Have you thought about executing your javascript after the page is loaded? You may use some frameworks like jQuery to facilitate crossbrowser issues. Or just put all your javascript code to the very bottom of body.