How to add onload event to a div element

前端 未结 24 2243
谎友^
谎友^ 2020-11-22 00:26

How do you add an onload event to an element?

Can I use:

for t

相关标签:
24条回答
  • 2020-11-22 00:37

    Use the body.onload event instead, either via attribute (<body onload="myFn()"> ...) or by binding an event in Javascript. This is extremely common with jQuery:

    $(document).ready(function() {
        doSomething($('#myDiv'));
    });
    
    0 讨论(0)
  • 2020-11-22 00:37

    Try this.

    document.getElementById("div").onload = alert("This is a div.");
    <div id="div">Hello World</div>

    Try this one too. You need to remove . from oQuickReply.swap() to make the function working.

    document.getElementById("div").onload = oQuickReplyswap();
    function oQuickReplyswap() {
    alert("Hello World");
    }
    <div id="div"></div>

    0 讨论(0)
  • 2020-11-22 00:40

    As all said, you cannot use onLoad event on a DIV instead but it before body tag.

    but in case you have one footer file and include it in many pages. it's better to check first if the div you want is on that page displayed, so the code doesn't executed in the pages that doesn't contain that DIV to make it load faster and save some time for your application.

    so you will need to give that DIV an ID and do:

    var myElem = document.getElementById('myElementId');
    if (myElem !== null){ put your code here}
    
    0 讨论(0)
  • 2020-11-22 00:41

    use an iframe and hide it iframe works like a body tag

    <!DOCTYPE html>
    <html>
    <body>
    
    <iframe style="display:none" onload="myFunction()" src="http://www.w3schools.com"></iframe>
    <p id="demo"></p>
    
    <script>
    function myFunction() {
        document.getElementById("demo").innerHTML = "Iframe is loaded.";
    }
    </script>
    
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-22 00:44

    onload event it only supports with few tags like listed below.

    <body>, <frame>, <iframe>, <img>, <input type="image">, <link>, <script>, <style>
    

    Here the reference for onload event

    0 讨论(0)
  • 2020-11-22 00:48

    we can use all these tags with onload

    <body>, <frame>, <frameset>, <iframe>, <img>, <input type="image">, <link>, <script> and <style>
    

    eg:

    function loadImage() {
        alert("Image is loaded");
    }
    <img src="https://www.w3schools.com/tags/w3html.gif" onload="loadImage()" width="100" height="132">

    0 讨论(0)
提交回复
热议问题