我怎么能做只运行一次的javascript

时间:2018-01-22 16:36:38

标签: javascript jquery

我有这个jquery代码:

$(document).ready(function(){
  $(".body").hide();

  setTimeout(function() {
    $(".body").show()
  }, 2000);

  setTimeout(function() {
    $(".img").fadeOut(1000)
  }, 1000);
});

我希望它只有在首次点击页面时才会起作用。因此,当您重新加载页面或浏览网站并导航回网站时,上面的脚本将无法执行。

3 个答案:

答案 0 :(得分:3)

您可以使用localStorage在浏览器级别存储值,因此下次用户访问您的网站时,他们将获得相同的数据。如果您在访问您的网站时设置了一个标记,那么您可以告诉他们第一次访问该网站,因为该标记未被设置。

以下是添加到您的代码中的更改,以及相应的注释...

$(document).ready(function(){

    // check localStorage to see if we've run this before.  If we have then do nothing
    if (!localStorage.getItem("first-run")) {

        // set a flag in localStorage so we know we've run this before.
        localStorage.setItem("first-run", true);

        $(".body").hide();

        setTimeout(function() {
            $(".body").show()
        }, 2000);

        setTimeout(function() {
            $(".img").fadeOut(1000)
        }, 1000);
    }
});

答案 1 :(得分:2)

尝试这样的事情。

$(document).ready(function() {
    if(!localStorage.visited) {
        //do first page load stuff
        ...
        localStorage.visited = true;
    }
});

答案 2 :(得分:1)

此处已有使用localStorage的解决方案;但是,localStorage中设置的值仍为until the user clears their browser data。这意味着你的代码永远不会再运行,除非你专门做了额外的工作来检查设置的时间等等。

如果您希望以后再访问该页面时再次运行,请使用sessionStorage

  

...存储在sessionStorage中的数据在页面会话时被清除   结束。 只要浏览器打开和,页面会话就会持续   幸存在页面重新加载和恢复。在新标签页中打开页面   或窗口将导致启动一个新的会话,这不同于   会话cookie如何工作。

这将允许代码在对页面的新访问时运行,但重新加载或导航/返回将不会触发它,因为sessionStorage仍然设置。但是,如果它们关闭选项卡/窗口并稍后返回,则代码将再次运行。

$(document).ready(function() {
    if(!sessionStorage.visited) {
        sessionStorage.visited = true;
        ...
        //other code
    }
});