Jquery.addClass from JSON not working correctly

http://jsfiddle.net/phongphan117/a212my20/ I have a json variable and use jquery.each()

to write html tag and create loop to add class to object. If you look at my code, it is not working correctly. How do I 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>
      

Run codeHide result


+3


source to share


1 answer


The problem is that you are passing some array

and some strings

, so when you have an array, the elements are each element inside, that is:

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

      

but when it is a string, each element is a letter, that is:

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

      

so you can just update the array class

to:



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

      

you will also have to update each of your functions as you add classes to the same .box

.

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

      

Now you add data.appearance

to your last .box

inserted!

and it will work! see jsfiddle https://jsfiddle.net/2z95ye56/1/

+2


source







All Articles