首页 > 解决方案 > 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>
      

 
    



           

标签: javascript

解决方案


在这种情况下,你可以做这样的事情。

代替:

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()]

推荐阅读