每次用户访问网站时只显示一次div

时间:2015-06-17 18:22:36

标签: javascript html

我尝试每次只显示一个div元素,用户在网站上。我已经看到了类似问题的多个答案,但它们似乎都没有工作......我写了一个代码,但它不起作用......我从某个地方得到了一部分代码否则(我无法记住)那么为什么它不起作用呢?

这是代码

<script type="text/javascript">
//<![CDATA[

var once_per_session=1


function get_cookie(Name) {
  var search = Name + "="
  var returnvalue = "";
  if (document.cookie.length > 0) {
    offset = document.cookie.indexOf(search)
    if (offset != -1) { // if cookie exists
      offset += search.length
      // set index of beginning of value
      end = document.cookie.indexOf(";", offset);
      // set index of end of cookie value
      if (end == -1)
         end = document.cookie.length;
      returnvalue=unescape(document.cookie.substring(offset, end))
      }
   }
  return returnvalue;
}

function alertornot(){
if (get_cookie('alerted')==''){
loadalert()
document.cookie="alerted=yes"
}
}

function loadalert(){
document.getElementById("popupp").style.visibility = visible;

if (once_per_session==0)
loadalert()
else
alertornot()

//]]>
</script>

<div class="popupp" style="visibility:hidden;">hi</div>

你认为你可以帮我弄清楚它有什么问题吗?

修改

我得到了它!这是:

<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
(function() {
    var visited = localStorage.getItem('visited');
    if (!visited) {
        document.getElementById("popupp").style.visibility = "visible";
        localStorage.setItem('visited', true);
    }
})();
}//]]>  

</script>


</head>
<body>
  <div id="popupp" style="visibility:hidden;">hi</div>

</body>

3 个答案:

答案 0 :(得分:6)

您可以使用localStorage,只有当用户清除它时,他才会再次获得弹出窗口(与Cookie相同)但更简单:

(function() {
    var visited = localStorage.getItem('visited');
    if (!visited) {
        document.getElementById("popupp").style.visibility = "visible";
        localStorage.setItem('visited', true);
    }
})();

HTML:

<div id="popupp" style="visibility:hidden;">hi</div>

这样您可以获得更少的代码。希望这会有所帮助。

答案 1 :(得分:0)

如果目标只是展示一次,您可以使用example on the MDN website作为开头。

if (document.cookie.replace(/(?:(?:^|.*;\s*)someCookieName\s*\=\s*([^;]*).*$)|^.*$/, "$1") !== "true") {
  alert("Do something here!");
  document.cookie = "someCookieName=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
}

http://jsfiddle.net/daCrosby/pqb5baa5/

修改

这里显示你的div。注意,我将样式移动到CSS而不是在我的jsFiddle中内联 - 更好的方法来获取

if (document.cookie.replace(/(?:(?:^|.*;\s*)someCookieName\s*\=\s*([^;]*).*$)|^.*$/, "$1") !== "true") {
    document.getElementById("popupp").style.visibility = "visbile";
    document.cookie = "someCookieName=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
}

http://jsfiddle.net/daCrosby/pqb5baa5/2/

答案 2 :(得分:0)

在html中试试class="popupp"更改为id="popupp"

并在javascript中:document.getElementById("popupp").style.visibility = visible;更改为document.getElementById("popupp").style.visibility = "visible";

Demo