我有一个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
})
))
})
答案 0 :(得分:1)
您可以这样添加Class:
//..
$('#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>