简体   繁体   中英

How to add class to specific img elemets in for loop in JavaScript

Now this code does not have any errors. And, I want to add a class "sprite" to all the img elements in the for loop. In addition, if eachName[1] is a.png or b.png, I want to add a class "found" to them, and otherwise I want to add a class "unfound". How can I write a code to achieve them. Thanks.

function populatePokedex() {

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "data.txt");
    xhr.onload = function(){
        if (this.status == 200) {

            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];
                document.getElementById("pokedex-view").innerHTML += "<img src=" + spriteurl + ">";
            }

        } else {
            document.getElementById("pokedex-view").innerHTML = "ERROR: Status: " + this.status + ", " + this.statusText;
        }
    }
    xhr.onerror = function(){
        document.getElementById("pokedex-view").innerHTML = "ERROR";
    }
    xhr.send();
}
...
    xhr.onload = function(){
        if (this.status == 200) {

            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] === 'a.png' || eachName[1] === 'b.png') {
                     imgClass += ' found';
                } else {
                     imgClass += ' unfound ';
                }
                document.getElementById("pokedex-view").innerHTML += '<img src="' + spriteurl + '" class="' + imgClass + '">';
            }

        } else {
            document.getElementById("pokedex-view").innerHTML = "ERROR: Status: " + this.status + ", " + this.statusText;
        }
    }
...

if rest of code is working, adding below lines will solve your problem.

...
var spriteurl = "/Pokedex/sprites/" + eachName[1];
img = document.createElement("img");
img.setAttribute("src", spriteurl);
klass = ["a.png", "b.png"].some(function(e) { return e == eachName[1]; } ? "found" : "unfound";
img.setAtrribute("class", klass) // or classList += 
document.getElementById("pokedex-view").appendChild(img); 
...

Usage of Array#some

Ternary operator

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