document.ready中的函数不起作用

时间:2014-03-11 06:23:19

标签: javascript jquery html cookies

我认为Jquery语法IM使用不正确,但不确定是什么问题。也许有人可以帮我一臂之力。所以我有一个HTML登录页面,它要求用户和pw。我想将这两个变量保存为会话cookie。

以下是登录的HTML:

            <FORM NAME="cf">
                <span class="auto-style1">Username:</span> 
                <input type="hidden" id="messageType" name="messageType" value="3">
                <INPUT TYPE="text" id="userName" NAME="userName" size="20" style="width: 180px">
                <br><span class="auto-style1">Password:</span> <INPUT TYPE="password" id="password" NAME="password" size="20" style="width: 180px">
                <span lang="en-ca">&nbsp;&nbsp;&nbsp;&nbsp; </span>
            </FORM>
            <INPUT TYPE="submit" id="btnSubmit" name="btnSubmit" Value="Sign In" style="width: 109px" class="auto-style2">

这是我写的Javascript:

$(document).ready(function () {
        $("#btnSubmit").click(function () {
            //collect userName and password
            var messageType = $("#messageType").val();
            var userName = $("#userName").val();
            var password = $("#password").val();
            var YouEntered;
            var YouEntered2;
            var cookie_name1 = "username";
            var cookie_name = "password";
            putCookie();
            putCookie2();

            auth(messageType, userName, password);
        });
    });

//Set Cookies username and password
function putCookie() {
if(document.cookie != document.cookie)
{index = document.cookie.indexOf(cookie_name1);}
else
{ index = -1;}

if (index == -1)
{
YouEntered=document.cf.userName.value;
document.cookie=cookie_name1+"="+YouEntered+"; expires=0"; //Expires when Session Ends
}
}

function putCookie2() {
if(document.cookie != document.cookie)
{index = document.cookie.indexOf(cookie_name);}
else
{ index = -1;}

if (index == -1)
{
YouEntered2=document.cf.password.value;
document.cookie=cookie_name+"="+YouEntered2+"; expires=0"; //Expires when Session Ends
}
}

如果我在HTML中使用onclick来运行putCookie函数,我可以保存cookie,但它不会发送到服务器。

感谢任何帮助或理由不起作用。

1 个答案:

答案 0 :(得分:0)

首先将您的功能更改为

function putCookie(cookie_name1) {
    if(document.cookie != your_cookie){
        index = document.cookie.indexOf(cookie_name1);
    }
    else {
        var YouEntered=document.cf.userName.value;
        document.cookie=cookie_name1+"="+YouEntered+"; expires=0"; //Expires when Session Ends
    }
}

并且应该像

一样调用函数
putCookie(cookie_name1);