来自JSON的jquery.addClass不正常工作

时间:2015-07-31 02:40:19

标签: javascript jquery html css json

http://jsfiddle.net/phongphan117/a212my20/ 我有一个json变量并使用jquery.each()来编写html标记并为对象中的add类创建循环。如果你查看我的代码,它就无法正常工作。如何修复它们?

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>

1 个答案:

答案 0 :(得分:2)

问题是,你传递了一些array和一些strings,所以当你有一个数组时,这些项目都是里面的项目,即:

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

但是当它是一个字符串时,每个项目都是一个字母,即:

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

因此您只需将class数组更新为:

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

您还需要更新每个功能,因为您要将类添加到同一个.box

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

现在,您要将data.appearance添加到上次插入的.box

它会起作用!看到j​​sfiddle https://jsfiddle.net/2z95ye56/1/