每次我从另一个页面重定向到模态显示的页面时,是否可以阻止我的模态显示



我正在使用Node express mongoose和ejs开发一个web应用程序。我有一个模式,当用户登录或注册并重定向到仪表板页面时显示。模态基本上是从引用API中提取的每日动机引用。

这是我的仪表板ejs文件中的模态:

<div id="modal-container">
<div id="modal">
<h5>✨Motivation of The Day✨</h5>
<span class="quote"></span>
<div id="close-btn">close</div>
</div>
</div>

这是我操作DOM:的js

let quote = document.querySelector('.quote')
let closeBtn = document.getElementById('close-btn')
let modalContainer = document.getElementById('modal-container')

window.addEventListener('load', async function() {
let quotes = []
const response = await fetch(`https://type.fit/api/quotes`)
const listOfQuotes = await response.json()
listOfQuotes.forEach(quote => quotes.push({quote: quote.text, author: quote.author}))
let random = Math.floor(Math.random() * quotes.length)
quote.innerText = quotes[random].quote


closeBtn.addEventListener('click', function() {
modalContainer.style.display = 'none'
})

})

此仪表板的路径是/dashboard。每次我做一些类似编辑帖子的事情时,都会转到一个新页面进行编辑,完成后,我会重定向回/dashboard路径,模态会再次弹出。

我如何确保modal只在用户登录/注册后显示,并且只显示一次,而不是每次用户重定向到/dashboard路由时都显示?

有人能给我指正确的方向吗?

很确定会发生这种情况,因为您将模态设置为每次加载窗口时都会出现,并且您没有检查用户是否满足模态实际出现的条件。当页面加载,用户导航到另一个页面时,模态会出现,当他们返回到/dashboard路由时,窗口上的事件侦听器再次启动,模态就会出现。

您可以在事件侦听器中包含一个条件检查,以查看用户是否登录,然后根据该值更改模态的显示。下面的基本示例。

HTML:

<body>
<div>
<h1>The text below will hide based on "login" state</h1>
<p class="login-text">The user is logged in</p>
</div>
</body>

JS:

const isLoggedIn = true;
const textToHide = document.querySelector(".login-text");
window.addEventListener("load", () => {
if (isLoggedIn === false) {
textToHide.style.display = "none";
} else {
textToHide.style.display = "block";
}})

至于处理用户登录的状态,您可以根据需要将该状态保存在localStorage或cookie中。

最新更新