[英]Set cookie on page load and hide div if cookie is present
I have a site that shows a modal window when the page is loaded. 我有一个网站,该页面在加载页面时显示模式窗口。 I want this to only be shown to visitors the first time they come to the site however. 但是,我希望仅向访问者第一次显示此内容。
I have set JavaScript to add a cookie on page load but I want that cookie to be read (if present) and hide the modal (if cookie present). 我已设置JavaScript在页面加载时添加cookie,但是我希望读取该cookie(如果存在)并隐藏模式(如果存在cookie)。
I have the following Javascript (no jQuery): 我有以下Javascript(无jQuery):
<script language="JavaScript">
if (document.cookie.indexOf('visited=true') == -1) {
var oneyear = 1000*60*60*24*365;
var expires = new Date((new Date()).valueOf() + oneyear);
document.cookie = "visited=true;expires=" + expires.toUTCString();
}
//Check if cookie is present and hide myModal DIV
if (document.cookie.indexOf('visited=true') >= 0) {
document.getElementById('myModal').modal.style.display = "none";
}
</script>
My Html is: 我的HTML是:
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="content">
<p>Text to be shown here</p>
<button id="closeBtn">Close</button>
</div>
</div>
</div>
The cookie is being set on the page load, but it's not being read on second page load and hiding #myModal Cookie是在页面加载时设置的,但在第二页面加载时未读取并隐藏#myModal
** Update** **更新**
I have updated the above code, following the answers below but now I have got an error in the Console: 我已经按照以下答案更新了上面的代码,但是现在控制台中出现错误:
Uncaught TypeError: Cannot read property 'style' of null
Modify this.You are checking string ( visited=true=
) wrong. 修改此内容。您正在检查字符串( visited=true=
)错误。 Set it to visited=true
or visited=
is the best option as per me 根据我的说法,将其设置为visited=true
或visited=
是最佳选择
if (document.cookie.indexOf('visited=') >= 0) {
document.getElementById('myModal').modal.style.display = "none";
}
You are checking the wrong string : 您正在检查错误的字符串:
if (document.cookie.indexOf('visited=true=') >= 0) {
should be 应该
if (document.cookie.indexOf('visited=true') >= 0) {
Could it be the .modal. 可能是.modal。 that needs to be removed? 需要删除? Ie change 即改变
if (document.cookie.indexOf('visited=') >= 0) {
document.getElementById('myModal').modal.style.display = "none";
}
to: 至:
if (document.cookie.indexOf('visited=') >= 0) {
document.getElementById('myModal').style.display = "none";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.