外部脚本中的window.onload在Javascript中被忽略 [英] window.onload in external script gets ignored in Javascript

查看:111
本文介绍了外部脚本中的window.onload在Javascript中被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

index.html

index.html

<html>
<head>
<script type="text/javascript" src="foo.js"></script>
<script type="text/javascript">
window.onload = function() {
    console.log("hello from html");
};
</script>
</head>
<body>
<div class="bar">bar</div>
</body>
</html>

foo.js

// this js file will be completely ignored with window.onload
//window.onload = function() {

    console.log("hello from external js");

    var bar = document.getElementsByClassName("bar");

    // this returns 0 instead of 1
    console.log(bar.length);
//};

  1. 在html中使用window.onload时,将忽略来自外部js的window.onload.
  2. 注释掉来自外部js的window.onload时,bar.length返回0.
  3. 从html中删除window.onload时,外部js中的window.onload正常工作.
  1. When window.onload is used in html, window.onload from external js will be ignored.
  2. When window.onload from external js is commented out, bar.length returns 0.
  3. When window.onload from html is removed, window.onload from external js works fine.

任何人都可以解释为什么我不能同时使用两个window.onload吗?

Can anyone explain why I can't use both window.onload?

如果我必须在html中使用window.onload,如何确定是否从外部js加载了窗口?

If I had to use window.onload in html, how do tell if window is loaded from external js?

推荐答案

1)以绑定的方式,可以只将一个方法附加到事件上.您需要添加所需的事件侦听器.

1)The way you're binding, you can have just one method attached to an event. You need to add an event listener for what you want.

window.addEventListener("load", function() { alert("hello!");});

直接将方法设置为onload事件将替换任何以前附加的方法.但是,如果改为使用侦听器,则可以将其中的许多绑定到事件.

Setting directly a method to the onload event will replace any previously attached method. But if you use listeners instead, you can have many of them bound to an event.

2)如果注释掉外部文件中的onload,则在调用document.getElementsByClassName("bar")时,您的文档尚未准备好,那么它将返回0个项目.

2)If you comment out the onload in your external file, when the document.getElementsByClassName("bar") is called, your document isn't ready yet, then, it will return 0 items.

3)使用我在第一点中解释过的addEventListener.如果您在两个地方都应用了此功能,它将像魅力一样发挥作用.

3)Use the addEventListener as I explained in the first point. If you apply this in both places, it will work like a charm.

这篇关于外部脚本中的window.onload在Javascript中被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆