简体   繁体   中英

How do I create and append an image with Javascript/jQuery?

I'm using the following code to create an image element, load it, then append it to the article on load.

$('<img />')
  .attr('src', 'image.png') //actually imageData[0].url
  .load(function () {
    $('article').append($(this));
    alert('image added');
  });

The alert is firing off ok, but the image doesn't appear, and when I inspect the element it has been added without the closing slash

<img src='image.png' >

Why is the browser removing the forward slash and how do I stop it?

UPDATE : Thanks to everyone who has pointed out that it's not the slash that's the problem (every day's a school day), so what could it be then? Here's the live example http://chris-armstrong.com/inspiration/?username=behoff

UPDATE 2 : Ok so it appears I'm a moron for not testing this with other images, as the issue seems to be with the test image I was using ( http://img.ffffound.com/static-data/assets/6/dc01f803819405bfe160459021cfe6cc57766f9b_m.jpg ). Strange because it loads when you click on the URL... but anyway, thanks for all your help folks, I learned a few things!

Based on the information provided, we know the following:

  • The image is successfully appended.

  • The image is successfully loaded (otherwise you wouldn't get the alert() ) .

Either you have an entirely transparent image (not likely of course) , or I'd bet that your CSS is somehow preventing its display.

Here's an example using the CSS that you commented out in your demo.

http://jsfiddle.net/JxhaR/ (No visible image)

Specifically, the culpret seems to be:

display: -webkit-box;

When I disable that, the image displays.

http://jsfiddle.net/JxhaR/1/ (Image is visible.)

Try this:

$('<img />')
    .attr('src', 'image.png')
    .append('article')
    .load(function(){
        alert('image added');
    });

When you inspect the element, you don't see it the way that it was added. Regardless if you add elements as HTML code or as elements (as in this case), when you inspect the code you are looking at code that was created from the element, you are not looking at the code that was used to add the element.

When you use $('<img />') it actually does a document.createElement('img') , so there is no HTML code where the ending slash can or can not be present. The element is created as a DOM object, it's not created from HTML code.

So, the reason that the image doesn't appear is not that there appears to be no ending slash in the tag.

The likely reason is that the image actually doesn't exist where the browser is looking for it, ie either the file is missing, or the URL is not correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM