我认为使用IM的Jquery语法不正确,但不确定是什么错误。也许有人可以帮我一下。因此,我有一个HTML登录页面,其中要求用户和密码。我想将这两个变量保存为会话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,但不会将其发送到服务器。

任何帮助或原因,它不起作用,不胜感激。

最佳答案

首先将您的功能更改为

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);

关于javascript - document.ready中的功能不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22317981/

10-11 16:26