admin管理员组文章数量:1327661
When adding an event listener for the load
I can't just use a function literal like I do for the click event. Why can't I use a function literal like I do for my click event?
<body>
<div>some content</div>
<script>
var div = document.getElementsByTagName("div")[0];
// does not work (console is not written to when page loads)...
div.addEventListener("load", function(){console.log("div load event")}, false);
// works (console is written to when div content is clicked...
div.addEventListener("click", function(){console.log("div click event")}, false);
</script>
</body>
When adding an event listener for the load
I can't just use a function literal like I do for the click event. Why can't I use a function literal like I do for my click event?
<body>
<div>some content</div>
<script>
var div = document.getElementsByTagName("div")[0];
// does not work (console is not written to when page loads)...
div.addEventListener("load", function(){console.log("div load event")}, false);
// works (console is written to when div content is clicked...
div.addEventListener("click", function(){console.log("div click event")}, false);
</script>
</body>
Share
Improve this question
edited Aug 13, 2016 at 14:57
jpishko
asked Aug 12, 2016 at 21:39
jpishkojpishko
1,0702 gold badges10 silver badges19 bronze badges
1
-
1
Divs don't fire
load
events. – Bergi Commented Aug 13, 2016 at 15:03
2 Answers
Reset to default 3The load
event fires in elements which load external contents, such as img
, iframe
, etc.
The truth is load
event may not fire case a content load before the event is declared. So, if you want the load
event to work, you need to declare it before a src
or href
, for example.
Once the div
is declared it's already loaded. So it's impossible to fire a event like this in the div
.
If you want to know the div
, including its elements such as img
have loaded, you must declare the load
event for each, i.e:
var loaded = 0;
var images = div.getElementsByTagName("img"),
len = images.length;
function imgload() {
if(++loaded > len) {
console.log("Div loaded.");
}
}
for(var i = 0, img; img = images[i]; i++) img.addEventListener("load", loaded);
When you add JS code for load event. Your load for div already finished. So load event will never be fired. And click works because it will appear later on when user click it. Read this to get better understanding.
https://developer.mozilla/en-US/docs/Web/Events/load
本文标签: javascriptWhy does addEventListener for load event not work with a divStack Overflow
版权声明:本文标题:javascript - Why does addEventListener for load event not work with a div? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742231007a2437213.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论