phongphan117
phongphan117

Reputation: 87

jquery.addClass from JSON isn't work correcly

http://jsfiddle.net/phongphan117/a212my20/ I have a json variable and use jquery.each()to write html tag and create loop for add class in the object. If you look at my code, it's not work correctly. How to fix them?

var db = {
    "class" : [
        {
            "appearance": ["red-bg", "white-text"]
        },
        {
            "appearance": ["yellow-bg", "black-text"]
        },
        {
            "appearance": "red"
        },
        {
            "appearance": "yellow"
        },
        {
            "appearance": ""
        }
    ]
}
$.each(db.class, function (key, data) {
        console.log(data);
        $('main').append('<div class="box">text</div>');
        for (i=0; i<data.appearance.length; i++) {
            var classtext = data.appearance[i].toString();
            $('.box').addClass(classtext);
        }
});
header, main, footer { padding-left: 0px; }
.box { width: 100px; height: 100px; }
.red-bg { background-color: red; }
.yellow-bg { background-color: yellow; }
.white-text { color: white; }
.black-text { color: black; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/2.2.1/isotope.pkgd.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.96.1/css/materialize.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.96.1/js/materialize.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
</main>

Upvotes: 3

Views: 287

Answers (1)

dpedoneze
dpedoneze

Reputation: 959

The problem is, you're passing some array and some strings, so when you have an array, the items are each item inside, ie:

["red-bg", "white-text"]
[0] = "red-bg"
[1] = "white-text"

but when it's a string, each item is a letter, ie:

"red"
[0] = "r"
[1] = "e"
[2] = "d"

so you can just update your class array to:

"class" : [
    {
        "appearance": ["red-bg", "white-text"]
    },
    {
        "appearance": ["yellow-bg", "black-text"]
    },
    {
        "appearance": ["red"]
    },
    {
        "appearance": ["yellow"]
    },
    {
        "appearance": [""]
    }
]

you'll also have to update your each function, since you're adding the classes to the same .box.

$('.box:last-child').addClass(data.appearance[i]);

Now you're adding the data.appearance to your last .box inserted!

and it'll works! see the jsfiddle https://jsfiddle.net/2z95ye56/1/

Upvotes: 2

Related Questions