gpt4 book ai didi

jquery - 在循环迭代时添加 CSS 类,JQuery

转载 作者:行者123 更新时间:2023-11-28 00:37:46 25 4
gpt4 key购买 nike

我有一个 jquery 循环,它创建了几个标题,每个标题下都有几个按钮。我需要为标题和按钮添加样式。现在它们在循环中被创建为 html 元素。我将如何在循环时添加 CSS 类而不是创建这些新的 html 元素,例如 <h3><button> ?这是我要完成的目标的屏幕截图。现在我的标题下面显示的是未设置样式的按钮,https://gyazo.com/2ab440e2792fc55dc32cdd39823ff0a9

    let response = [{
"name": "Study",
subSection: "Education"
}, {
"name": "Classes",
subSection: "Education"
},
{
name: "Society",
subSection: "Social"
}
];

let res = response.reduce((obj, item) => {
obj[item.subSection] = obj[item.subSection] || [];
obj[item.subSection].push(item.name);
return obj;
}, {});


// get values array and iterate
Object.keys(res).forEach(function(k) {
// generate h3 ith subSection value and append
$('#container').append(
$('<h3>', {
text: k
})
)
// generate buttons and append
.append(res[k].map(v =>
$('<button>', {
text: v
})
))
})

最佳答案

你可以这样添加类:

//..
$('#container').append(
$('<h3 class="tit_article">' + k + '</h3>')
)

//.. OR

.append(res[k].map(v =>
$(`<button class="btn_del">${v}</button>`)
))
//...

let response = [{
"name": "Study",
subSection: "Education"
}, {
"name": "Classes",
subSection: "Education"
},
{
name: "Society",
subSection: "Social"
}
];

let res = response.reduce((obj, item) => {
obj[item.subSection] = obj[item.subSection] || [];
obj[item.subSection].push(item.name);
return obj;
}, {});


// get values array and iterate
Object.keys(res).forEach(function(k) {
// generate h3 ith subSection value and append
$('#container').append(
$('<h3 class="tit_article">' + k + '</h3>')
)
// generate buttons and append
.append(res[k].map(v =>
$(`<button class="btn_del">
<img src="/wwwroot/images/${v}.svg">
${v}
</button>`)
))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container"></div>

关于jquery - 在循环迭代时添加 CSS 类,JQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55213329/

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