Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我的javascript函数在没有被调用的情况下运行有什么原因吗?_Javascript_Jquery_Cookies - Fatal编程技术网

我的javascript函数在没有被调用的情况下运行有什么原因吗?

我的javascript函数在没有被调用的情况下运行有什么原因吗?,javascript,jquery,cookies,Javascript,Jquery,Cookies,我正在运行一个脚本来验证用户年龄。用于检查cookie的函数在用户第一次进入页面时起作用,如果用户没有请求的cookie,则会重定向到年龄验证所在的主页 一旦发生这种情况,实际上会在重定向上创建cookie,此时用户可以转到站点的任何子页面。有人能指出为什么会发生这种情况吗 //Setting The Value Of The Cookie var this_cookies_value = "_addMeToTheBrowser_"; //Checks page on

我正在运行一个脚本来验证用户年龄。用于检查cookie的函数在用户第一次进入页面时起作用,如果用户没有请求的cookie,则会重定向到年龄验证所在的主页

一旦发生这种情况,实际上会在重定向上创建cookie,此时用户可以转到站点的任何子页面。有人能指出为什么会发生这种情况吗

    //Setting The Value Of The Cookie
    var this_cookies_value = "_addMeToTheBrowser_";

    //Checks page on load to see if this_cookies_value already exists
    function checkForOurCookiesValue() {
    var allTheCookies = document.cookie;
    var _this_Host_Name_ = '"' + window.location.hostname + '"';
    var _this_Path_Name = window.location.pathname;

    console.log(allTheCookies);

    if(allTheCookies.includes(this_cookies_value) || _this_Path_Name == "/") {
    console.log("WORKING");
    } else {
    window.location.replace(_this_Host_Name_);
    };

    }
    checkForOurCookiesValue();


    //If cookie does not exist, this script will run once users age is verified correctly
    function createCookie(name,value,days) {

    if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
    return true;
    }
    //Creating the cookie
    jQuery(".the_btn").on("click", createCookie("_my_domain_", this_cookies_value, 1));`enter code here`

您需要在最后一行中将函数设置为匿名(匿名)函数

你的代码 正确代码 当浏览器读取代码时,它会将
createCookie()
视为需要立即运行的函数调用。如果将其放入匿名函数中,则不会调用它,而是创建另一个函数,稍后由
单击
事件调用

考虑到您正在使用jQuery,我假设您需要完全的浏览器支持,而IE还不支持功能;但是,如果您不需要IE支持,可以使用以下代码:

jQuery(".the_btn")
  .on(
    "click",
    () => createCookie("_my_domain_", this_cookies_value, 1)
  );
演示

您调用代码最后一行中的函数,您可能打算编写
jQuery(“.the_btn”)。在(“单击”,函数(事件){createCookie(“\u我的\u域”,此\u Cookie_值,1);})
on('click',createCookie(…)
on('click',function(){createCookie(…)})
ah,是的,谢谢大家。现在问题解决了@贝吉
jQuery(".the_btn")
  .on(
    "click",
    function() {
      createCookie("_my_domain_", this_cookies_value, 1)
    }
  );
jQuery(".the_btn")
  .on(
    "click",
    () => createCookie("_my_domain_", this_cookies_value, 1)
  );