每个会话如何关闭一次onclick?

时间:2019-05-07 11:21:04

标签: javascript php

我写了这个简单的代码来单击X后关闭跨度,但是每次刷新页面或进入另一页面时都会加载。

function hinweisClose() {
                var x = document.getElementById("hinweis_header"); {
                        x.style.display = "none";
                }
        }

这是php中的代码:

<div id="hinweis_header">
    <span style="vertical-align: middle; padding-top: 20px; font-weight: bold;"><a href="<?=SHOP_URL_HTTPS?>/<?=$param["links"]["service"]?>/<?=$sprachdatei["links"]["link_hinweis"]?>"><b>Nur heute: 10 % auf alle Jersey Stoffe >><?=$sprachdatei['header']['hinweis_header']?></b></a></span>
    <div class="close-btn" style="position: absolute; display: inline-block; top: -4px; padding-right: 6px; color: #fff;"><span class="rwd-buttinette-icon rwd-icon-remove-circle-1" onclick="hinweisClose()" style="float: right;"></span></div>
</div>

我已经尝试了sessionStorage,但无法使其正常工作:

if (sessionStorage.getItem('HinweisOnce') !== 'true') {
        function hinweisClose() {
                var x = document.getElementById("hinweis_header"); {
                        x.style.display = "none";
                }
        }
    sessionStorage.setItem('HinweisOnce','true');
   }

我希望它仅加载一次,直到关闭并在该会话中保持关闭状态。有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

关闭跨度后,添加一个cookie,例如:

document.cookie = "popup=closed";

然后,您可以在再次显示跨度之前检查cookie,例如:

isClosed = document.cookie.replace(/(?:(?:^|.*;\s*)popup\s*\=\s*([^;]*).*$)|^.*$/, "$1") === "closed";
if(isClosed) {
    displayMySpan();
}

您可以阅读有关JS cookie here的更多信息。

对于基于PHP的解决方案,您仍然可以在关闭跨度后设置cookie,例如:

document.cookie = "popup=closed; path=/";

然后在您的PHP代码中,您需要以下内容:

if (isset($_COOKIE['popup']) && $_COOKIE['popup'] === "closed") {
    //code to display div here
};
相关问题