javascript - 来自 JSON 的 jquery.addClass 无法正常工作

标签 javascript jquery html css json

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

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>

最佳答案

问题是,你正在传递一些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 中!

它会起作用的!查看 jsfiddle https://jsfiddle.net/2z95ye56/1/

关于javascript - 来自 JSON 的 jquery.addClass 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31737256/

相关文章:

javascript - PHP AJAX - &lt;input&gt; 元素可以像 <form> 一样具有 "action"吗?

javascript - 检查所有在 wamp 中不起作用的复选框

javascript - 有人可以解释这两个 http 调用之间的区别以及为什么一个失败而另一个没有失败吗?

javascript - d3.js 从下到上强制布局 - 拖动行为

javascript - 在 Chrome 浏览器上呈现导航栏的问题

javascript - useEffect,覆盖if语句

javascript - Uncaught TypeError : app. all is not a function

javascript - 您可以停止 HTML5 视频在滚动时暂停/停止吗?

jquery - 移动浏览器上的粘性 header

javascript - 如何防止javascript更改输入值