用JS在页面加载时隐藏div.代码问题



我想根据用户的登录状态显示顶部菜单。区别如下:

  • Zaloguj -未登录用户

  • Wyloguj -登录用户

我需要的代码工作时,一个页面正在加载,但它不是。下面的代码有什么问题?

<div>
<div id="non_loggedIn" style="display:block">
Baza wiedzy - 1
</div>
<div id="loggedIn" style="display:block">
Baza wiedzy - 2
</div>
<div id="login-status">
Zaloguj
</div>
</div>

和JS代码:

window.onload = function() {
var loginStatus = document.getElementById('login-status').innerText;
var loggedIn = document.getElementById('loggedIn').style.display;
var non_loggedIn = document.getElementById('non_loggedIn').style.display;

console.log('loggedIn: ' + loggedIn);
console.log('non-loggedIn: ' + non_loggedIn);
console.log('loginStatus: ' + loginStatus);
if (loginStatus == 'Zaloguj') {
loggedIn = 'block'
non_loggedIn = 'none'
} else {
loggedIn = 'none'
non_loggedIn = 'block'
}

console.log('loggedIn: ' + loggedIn);
console.log('non-loggedIn: ' + non_loggedIn);
console.log('loginStatus: ' + loginStatus);
}

链接到jsfiddle: https://jsfiddle.net/xmves0qb/

您当前只是更改存储在变量中的值。如果将实际的HTML元素存储在变量中,则可以在If中更改其样式。

window.onload = function() {
const loginStatus = document.getElementById('login-status').innerText;
const loggedIn = document.getElementById('loggedIn'); // removed style.display here
const non_loggedIn = document.getElementById('non_loggedIn'); // removed style.display here
if (loginStatus == 'Zaloguj') {
loggedIn.style.display = 'block' // added style.display here
non_loggedIn.style.display = 'none' // added style.display here
} else {
loggedIn.style.display = 'none' // added style.display here
non_loggedIn.style.display = 'block' // added style.display here
}
}
<div>
<div id="non_loggedIn" style="display:block">
Baza wiedzy - 1
</div>
<div id="loggedIn" style="display:block">
Baza wiedzy - 2
</div>
<div id="login-status">
Zaloguj
</div>
</div>

相关内容

  • 没有找到相关文章

最新更新