gpt4 book ai didi

javascript - 代码优化: style display

转载 作者:行者123 更新时间:2023-12-01 02:27:06 26 4
gpt4 key购买 nike

我根据不同的 session 制作了这两个函数,根据 session 显示/隐藏不同的 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";

}

最佳答案

您可以像这样分隔共享样式更改:

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";
}

您可以创建用于显示和隐藏的辅助函数:

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);
}

关于javascript - 代码优化: style display,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48667690/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com