Adding images to an HTML document with javascript

后端 未结 6 1928
故里飘歌
故里飘歌 2020-11-30 04:22

I\'ve tried some HTML DOM code from several sites, but it isn\'t working. It isn\'t adding anything. Does anyone have a working example on this?

this.img =          


        
相关标签:
6条回答
  • 2020-11-30 04:32

    This works:

    var img = document.createElement('img');
    img.src = 'img/eqp/' + this.apparel + '/' + this.facing + '_idle.png';
    document.getElementById('gamediv').appendChild(img)
    

    Or using jQuery:

    $('<img/>')
    .attr('src','img/eqp/' + this.apparel + '/' + this.facing + '_idle.png')
    .appendTo('#gamediv');
    
    0 讨论(0)
  • 2020-11-30 04:39

    or you can just

    <script> 
    document.write('<img src="/*picture_location_(you can just copy the picture and paste   it into the script)*\"')
    document.getElementById('pic')
    </script>
    <div id="pic">
    </div>
    
    0 讨论(0)
  • 2020-11-30 04:42

    With a little research i found that javascript does not know that a Document Object Exist unless the Object has Already loaded before the script code (As javascript reads down a page).

    <head>
        <script type="text/javascript">
            function insert(){
                var src = document.getElementById("gamediv");
                var img = document.createElement("img");
                img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
                src.appendChild(img);
            }
         </script>
     </head>
     <body>
         <div id="gamediv">
             <script type="text/javascript">
                 insert();
             </script>
         </div>
     </body>
    
    0 讨论(0)
  • 2020-11-30 04:43

    You need to use document.getElementById() in line 3.

    If you try this right now in the console:

    var img = document.createElement("img");
    img.src = "http://www.google.com/intl/en_com/images/logo_plain.png";
    var src = document.getElementById("header");
    src.appendChild(img);
    <div id="header"></div>

    ... you'd get this:

    0 讨论(0)
  • 2020-11-30 04:43

    Get rid of the this statements too

    var img = document.createElement("img");
    img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
    src = document.getElementById("gamediv");
    src.appendChild(this.img)
    
    0 讨论(0)
  • 2020-11-30 04:47

    Things to ponder:

    1. Use jquery
    2. Which this is your code refering to
    3. Isnt getElementById usually document.getElementById?
    4. If the image is not found, are you sure your browser would tell you?
    0 讨论(0)
提交回复
热议问题