javascript - JavaScript:如何使用较少重复的代码重构 if..else 语句?
问题描述
我有一个服务器生成的模板,其中包含多个带有 idbook_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;
}
<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>
解决方案
在这种情况下,你可以做这样的事情。
代替:
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;
}
你可以这样做:
book_cat_id2.style.backgroundColor = colors[id2.toLowerCase()]
推荐阅读
- java - 在 Assert.fail() 之后 Java 程序不会终止
- c++ - 在控制台关闭之前启用多个输入
- javascript - 无法将 JavaScript 对象记录到控制台,不断收到“未定义”
- c++ - 如何从 C++ 中的 get 函数返回多个结构值?
- java - Windows 10 java -version 与 JAVA_HOME 不同
- javascript - 无法将用户状态信息记录到脚本
- pandas - 在给定 UTC 时间的特定邮政编码处查找本地日期时间
- javascript - 找不到角度导出
- google-cloud-platform - 错误 400:请求包含无效参数 - Google Cloud Identity API
- .net - 作为 Windows 的“组件”的 .NET Framework 版本的支持结束日期