单击并使用LocalStorage保存后如何隐藏横幅? [英] How to Hide Banner after click and Save with LocalStorage?
问题描述
我是Java脚本的新手,在用户单击Cookie横幅上的接受"后,我不知道如何保存信息(本地存储)-当他单击接受"时,Cookie横幅消失了,我会想要保存此信息,因此他在转到下一页或重新加载时不会再次获得Cookie横幅.
I'm new to Java Script and I can't figure out how to save the Information (localstorage) after the User clicks on Accept on my Cookie Banner - As soon as he clicks on Accept the Cookie Banner disappears and I would like to save this information, so he doesnt get the Cookie Banner again as soon as he goes to the next page or reloads it.
非常感谢您能提供的任何帮助.
I'm thankfull for any help you can provide.
这是我的代码:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#Accept").click(function(){
$('#CookieBanner').hide();
});
});
</script>
<div id="CookieBanner">
<div class="agj">
<div class="agj-content">
<div class="initial-info">
<h2 class="title">Privacy</h2>
<p class="message">
This website uses cookies to provide you with the best possible service and website functionality, and to provide social media features and analyse the traffic to our website. If you continue to use our website, you agree to our using cookies.
</p>
</div>
<div class="buttons">
<button id="Accept">Accept</button>
<a class="link" href="#" title="Get more Information about Cookies and how we use them">Show Purposes</a>
</div>
</div>
</div>
</div>
推荐答案
使用 getItem
和 setItem
方法足以解决问题
Using getItem
and setItem
methods is enough to solve it
$(document).ready(function(){
// Check if the user already accepted it
if (window.localStorage.getItem('accept_cookies')) {
$('#CookieBanner').hide();
}
$("#Accept").click(function(){
// Save on LocalStorage
window.localStorage.setItem('accept_cookies', true);
$('#CookieBanner').hide();
});
});
您可以在MDN网络文档上阅读有关localStorage的更多信息:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/localStorage
You can read more about localStorage on MDN web docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
这篇关于单击并使用LocalStorage保存后如何隐藏横幅?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!