简体   繁体   中英

How to add multiple classes to an img element

I am tring to add a class sprite to all the images. Moreover if eachName[1] is bulbasaur, I want to add a class found to it, and otherwise I want to add a class unfound to them. This code could catch a class sprite correctly, but could not catch found/unfound. Is there something wrong in this code? Thanks.

            var picArr = this.responseText.split("\n");
            for(var i=0; i < picArr.length; i++){
                var eachName = picArr[i].split(":")
                var spriteurl = "/Pokedex/sprites/" + eachName[1];
                var imgClass = 'sprite';
                if(eachName[1]==='bulbasaur.png'){
                    imgClass += ' found';
                } else {
                    imgClass += ' unfound';
                }
                document.getElementById("pokedex-view").innerHTML += "<img src=" + spriteurl + " class=" + imgClass + ">";
            }

I think you're missing escaped quotes in your innerHTML output.

document.getElementById("pokedex-view").innerHTML += "<img src=\"" + spriteurl + "\" class=\"" + imgClass + "\">";

Also, if you want to add the class found and unfound it should be :

            if(eachName[1]==='bulbasaur.png'){
                imgClass += ' found';
            } else {
                imgClass += ' unfound';
            }

Otherwise you're losing the sprite class by re-assigning the imgClass variable instead of appending to it.

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