0

I have a list that looks like this:

<ul>
    <li>nameID0001</li>
    <li>nameID0002</li>
    <li>nameID0003</li>
    <li>nameID0004</li>
</ul>

I know there is a photo associated with the name. It is 'nameID0001.jpg' or 'nameID0001.png'.

I want to insert a picture after name:

$('ul li').each(function () {
    var nameID = $(this).text();
    $(this).append('<img src="/images/' + nameID + '.jpg" alt="" />');
});

How to recognize whether a file exists and whether it has a jpg or png extension.

If it doesn't exist insert 'default.jpg', otherwise insert with the appropriate extension.

Lech
  • 61
  • 2
  • Possible duplicate of [Check if an image is loaded (no errors) in JavaScript](http://stackoverflow.com/questions/1977871/check-if-an-image-is-loaded-no-errors-in-javascript) – Douwe de Haan May 04 '17 at 10:06

1 Answers1

0

Try changing the img src using javascript, while the remote image file not exist.

Add an onerror to the IMG node:

 <IMG src="http://www.baidu.com/img/baidu_logo.gif" onerror="javascript:this.src='/images/logo.jpg'">

this codes works for me:

  <ul>
    <li>nameID0001</li>
    <li>nameID0002</li>
    <li>nameID0003</li>
    <li>nameID0004</li>
</ul>

<script type="text/javascript">

    function changesrc(obj, nameID1) {
        var src1 = obj.src.replace(".jpg", ".png");
        //ignore error while .png file not exist
        if(src1 == obj.src) return;
        obj.src = src1;
    }

    $('ul li').each(function () {
        var nameID = $(this).text();
        $(this).append('<img src="/images/' + nameID + '.jpg" onerror="javascript:changesrc(this);" />');
    });

</script>
chris
  • 80
  • 7