最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why does addEventListener for load event not work with a div? - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 3

The 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

发布评论

评论列表(0)

  1. 暂无评论