代码优化:样式显示

时间:2018-02-07 15:37:49

标签: javascript optimization

我根据不同的会话制作了这两个功能,根据会话显示/隐藏不同的HTML代码。关于如何简化这个问题的任何想法?如果有可能用更少和更好的代码编写它?

// HTML / user interface for ADMIN view
function showAdminInterface() {       
      lblDropdown.style.display = "flex";
      lblDropdownforMobileOnly.style.display ="none";
      btnCreateProduct.style.display = "flex"; 
      btnCreateUser.style.display = "flex";
      pageViewProducts.style.display ="flex";
      btnSignupNav.style.display = "none";
      btnLoginNav.style.display = "none";
      btnSubscribeNav.style.display = "none";

}

  /************************************************************************/
  /************************************************************************/
  /************************************************************************/


  // HTML / user interface for USER view
  function showUserInterface() {

      lblDropdown.style.display = "flex";
      lblDropdownforMobileOnly.style.display ="none";
      pageViewProducts.style.display ="flex";
      btnEditUsersNav.style.display = "none";
      btnEditProductsNav.style.display = "none";
      btnViewSubscribersNav.style.display = "none";
      btnCreateProduct.style.display = "none";
      btnCreateUser.style.display = "none";
      btnSignupNav.style.display = "none";
      btnLoginNav.style.display = "none";

  }

2 个答案:

答案 0 :(得分:1)

您可以将共享样式更改分开,如下所示:

function initInterface() {
    lblDropdown.style.display = "flex";
    lblDropdownforMobileOnly.style.display ="none";
    pageViewProducts.style.display ="flex";
    btnSignupNav.style.display = "none";
    btnLoginNav.style.display = "none";
}

function showAdminInterface() {  
    initInterface();
    btnCreateProduct.style.display = "flex"; 
    btnCreateUser.style.display = "flex";
    btnSubscribeNav.style.display = "none";
}


function showUserInterface() {
    initInterface();
    btnEditUsersNav.style.display = "none";
    btnEditProductsNav.style.display = "none";
    btnViewSubscribersNav.style.display = "none";
    btnCreateProduct.style.display = "none";
    btnCreateUser.style.display = "none";
}

你可以为show和hide创建帮助函数:

function hide(el) {
    el.style.display = "none"; // you can do the same with show and flex
}

function showUserInterface() {
    initInterface();
    hide(btnEditUsersNav);
    hide(btnEditProductsNav);
    hide(btnViewSubscribersNav);
    hide(btnCreateProduct);
    hide(btnCreateUser);
}

function showUserInterface() {
    initInterface();

    [
        btnEditUsersNav,
        btnEditProductsNav,
        btnViewSubscribersNav,
        btnCreateProduct,
        btnCreateUser
    ].forEach(hide);
}

答案 1 :(得分:1)

仅举例来说,但你明白了。

 function showInterface(isAdmin = false) {
     lblDropdown.style.display = isAdmin ? "flex" : "none";
     ... // the rest
 }