What is the best JavaScript code to create an img element

前端 未结 11 1917
攒了一身酷
攒了一身酷 2020-11-28 20:46

I want to create a simple bit of JS code that creates an image element in the background and doesn\'t display anything. The image element will call a tracking URL (such as

相关标签:
11条回答
  • 2020-11-28 21:15

    As others pointed out if you are allowed to use a framework like jQuery the best thing to do is use it, as it high likely will do it in the best possible way. If you are not allowed to use a framework then I guess manipulating the DOM is the best way to do it (and in my opinion, the right way to do it).

    0 讨论(0)
  • 2020-11-28 21:16

    Are you allowed to use a framework? jQuery and Prototype make this sort of thing pretty easy. Here's a sample in Prototype:

    var elem = new Element('img', { 'class': 'foo', src: 'pic.jpg', alt: 'alternate text' });
    $(document).insert(elem);
    
    0 讨论(0)
  • 2020-11-28 21:20

    you could simply do:

    var newImage = new Image();
    newImage.src = "someImg.jpg";
    
    if(document.images)
    {
      document.images.yourImageElementName.src = newImage.src;
    }
    

    Simple :)

    0 讨论(0)
  • 2020-11-28 21:24

    Just for the sake of completeness, I would suggest using the InnerHTML way as well - even though I would not call it the best way...

    document.getElementById("image-holder").innerHTML = "<img src='image.png' alt='The Image' />";
    

    By the way, innerHTML is not that bad

    0 讨论(0)
  • 2020-11-28 21:25

    Just to add full html JS example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>create image demo</title>
        <script>
    
    
            function createImage() {
                var x = document.createElement("IMG");
                x.setAttribute("src", "http://www.iseebug.com/wp-content/uploads/2016/09/c2.png");
                x.setAttribute("height", "200");
                x.setAttribute("width", "400");
                x.setAttribute("alt", "suppp");
                document.getElementById("res").appendChild(x);
            }
    
        </script>
    </head>
    <body>
    <button onclick="createImage()">ok</button>
    <div id="res"></div>
    
    </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题