只调用一次函数

Car*_*las 6 javascript jquery

我有3个div(#Mask #Intro #Container)所以如果你点击Mask,Intro会被隐藏并且容器会出现.问题是我只想加载一次,不是每次刷新页面或任何时候点击菜单或链接等.

我怎样才能做到这一点?

这是我现在使用的脚本:

$(document).ready(function(){
    $("div#mask").click(function() {
        $("div#intro").fadeToggle('slow');
        $("div#container").fadeToggle('slow');
        $("div#mask").css("z-index", "-99");
    });
});
Run Code Online (Sandbox Code Playgroud)

谢谢!

Yes*_*rry 8

您可以尝试使用简单的计数器.

// count how many times click event is triggered
var eventsFired = 0;
$(document).ready(function(){
    $("div#mask").click(function() {
        if (eventsFired == 0) {
            $("div#intro").fadeToggle('slow');
            $("div#container").fadeToggle('slow');
            $("div#mask").css("z-index", "-99");
            eventsFired++; // <-- now equals 1, won't fire again until reload
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

坚持这一点,您需要设置一个cookie.(例如,$.cookie()如果您使用该插件).

// example using $.cookie plugin
var eventsFired = ($.cookie('eventsFired') != null)
    ? $.cookie('eventsFired')
    : 0;

$(document).ready(function(){
    $("div#mask").click(function() {
        if (eventsFired == 0) {
            $("div#intro").fadeToggle('slow');
            $("div#container").fadeToggle('slow');
            $("div#mask").css("z-index", "-99");
            eventsFired++; // <-- now equals 1, won't fire again until reload
            $.cookie('eventsFired', eventsFired);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

要在以后删除cookie:

$.cookie('eventsFired', null);
Run Code Online (Sandbox Code Playgroud)


vsy*_*ync 5

一旦被调用,只需指向一个空函数.

var myFunc = function(){
     myFunc = function(){}; // kill it
     console.log('Done once!'); // your stuff here
};
Run Code Online (Sandbox Code Playgroud)