gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:29:50 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com