我有一个包含有ID的多个元素的服务器生成的模板book_cat_id,book_cat_id2等我需要找到并改变他们的直列背景颜色,以配合相应的类别
data-cat_label="Fiction" 可以有小说、幻想、漫画、历史、技术中的任何一种
对于多种颜色,是否有更有效的方法?
const colors = {
fiction: "#ff7477",
fantasy: "#7dbb65",
technical: "#BC9DCA",
comic: "#00A2E0",
history: "#ff0099",
health: "#f59e2e"
}
let id1 = book_cat_id.getAttribute("data-cat_label");
let id2 = book_cat_id2.getAttribute("data-cat_label");
if(id1 === 'Fiction') {
book_cat_id.style.backgroundColor = colors.fiction;
}else if (id1 === 'Fantasy') {
book_cat_id.style.backgroundColor = colors.fantasy;
}else if (id1 === 'Comic') {
book_cat_id.style.backgroundColor = colors.comic;
}else if (id1 === 'History') {
book_cat_id.style.backgroundColor = colors.history;
}
if(id2 === 'Fiction') {
book_cat_id2.style.backgroundColor = colors.fiction;
}else if (id2 === 'Fantasy') {
book_cat_id2.style.backgroundColor = colors.fantasy;
}else if (id2 === 'Comic') {
book_cat_id2.style.backgroundColor = colors.comic;
}else if (id2 === 'History') {
book_cat_id2.style.backgroundColor = colors.history;
}Run Code Online (Sandbox Code Playgroud)
<table>
<tr>
<td id="book_cat_id" data-cat_label="Fiction" style="background-color:#ff0000;">
Book
</td>
</tr>
<tr>
<td id="book_cat_id2" data-cat_label="Fantasy" style="background-color:#ff0000;">
Book
</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
在这种情况下,你可以做这样的事情。
代替:
if(id2 === 'Fiction') {
book_cat_id2.style.backgroundColor = colors.fiction;
}else if (id2 === 'Fantasy') {
book_cat_id2.style.backgroundColor = colors.fantasy;
}else if (id2 === 'Comic') {
book_cat_id2.style.backgroundColor = colors.comic;
}else if (id2 === 'History') {
book_cat_id2.style.backgroundColor = colors.history;
}
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
book_cat_id2.style.backgroundColor = colors[id2.toLowerCase()]
Run Code Online (Sandbox Code Playgroud)