如何在身体的加载事件上获取cookie?

时间:2014-01-25 12:00:00

标签: javascript jquery cookies

我有一个像这样的对话框

<div id="savedialog"  class="pop1">      
    <div id="center" style="margin:30px;">
        <h1 style="font-size:20px;color:#000;margin-bottom:0;">Ready to Save Your Quote?</h1>
        <p style="font-size:12px;margin-bottom:0;">
            <span style="font-weight:bold;">Email</span>
            <input style="margin-bottom:15px; margin-left:90px;" type="text" id="email"  name="email" placeholder="" />
            <p style="font-size:12px;margin-bottom:0;">
                <span style="font-weight:bold;">Confirm Email</span>
                <input style="margin-bottom:15px; margin-left:40px;" type="text" id="confirm_email"  name="confirm_email" placeholder="" />
            </p>
            <hr style="border-bottom:1px dotted #ccc;">
        </p>
        <p>
            <input type="hidden" name="action" value="popshow"/>    
            <input class="btn btn-primary btn-large" type="button" id="directory" value="Save quote" > &nbsp;&nbsp;&nbsp;
            <a href="#" id="cnl24">Cancel</a>
        </p>
    </div>
</div> 

现在,我按照代码显示并隐藏了对话框,并在该代码中设置了cookie

$(function(){
    $('#saveandcontinue').click(function() {    
        $('#savedialog').show("slow");         
    });

    $('#directory').click(function(){
        var email = document.getElementById('email').value;
        document.cookie="emailID="+email; "path=/";
        $('#savedialog').hide("slow");
        location.href='03_drivers.php';
        alert("your Quotre has been saved");
    });

    $('#cnl24').click(function(){
        $('#savedialog').hide("slow");
    });
});

我已经调用了像这样的检查cookie的函数

<body onload="checkCookie();">

并通过checkcookie函数定义检查cookie

function checkCookie() {
    alert("yes");
    var user=getCookie("email");

    if (user!="")
        alert("Welcome again ");
    else
        alert("not set");
}

但没有得到任何cookie所以请你能告诉我我错在哪里。

1 个答案:

答案 0 :(得分:2)

如果您没有定义getCookie功能,请使用此

function getCookie(cname){
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) 
      {
      var c = ca[i].trim();
      if (c.indexOf(name)==0) return c.substring(name.length,c.length);
      }
    return "";
}

您正在使用document.cookie="emailID="+email; "path=/";设置带有'emailId'的Cookie并使用email =getCookie("email");