简体   繁体   中英

Using JavaScript to dynamically change display style in img tags

I show links to 240 images on a page. The real images are uploaded by users. I tried to avoid showing an empty image if users did not upload it yet. jQuery did not work for me because of conflicts, so I have to do it in pure JavaScript.

image(s) links:

<img class="photo240" src="http://www.example.com/i/%%GLOBAL__AuthorID%%/p/b01.jpg" onerror="imgError()">

My JavaScript:

function imgError()
{
    alert('The image could not be loaded.');
    var _aryElm=document.getElementsByTagName('img');  //return an array with every <img> of the page
    for( x in _aryElm) {
        _elm=_aryElm[x];
        _elm.className="photo240off";
    }
}

The style photo240off equals to display:none .

Right now, whenever an image misses, all the images are turned to style photo240off and I want only the missing image to be hidden. So there is something wrong with my script.

(the overall script works well, because I get the alert).

Use this to get the image with the error.

Change to:

onerror="imgError(this)"

Then the function can be:

function imgError(el) {
    alert('The image could not be loaded.');
    el.className = "photo240off";
}

You need to reference the image from your onerror call and change the class only for that one.

Something like this:

HTML

<img class="photo240" src="example.jpg" onerror="imgError(this)">

JS

function imgError(el) {
    el.className="photo240off";
}

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