-3

有人可以帮我做作业吗?

<div id="header">
    <form id="login" onsubmit="return member()">
        <p>
            <label for="txtuser">User:</label>
            <input type="text" class="text" name="txtuser" id="txtuser"/><br/>
            <label for="txtpass">Password:</label> 
            <input type="text" class="text" name="txtpass" id="txtpass"/><br/>
            <input type="submit" class="buttons" id="btnlogin" name="btnlogin" value="Login"/>
        </p>
    </form>
</div>

这是我的作业,我有一个登录表单,其中包含用户名和密码文本框,我必须验证表单,如果它有效,一旦用户成功登录,网站的每个页面都会显示用户的登录名,以及带有允许他们随时注销的链接。我该怎么办?cookies也需要...还是谢谢

4

1 回答 1

2

在 member() 函数中,您可以使用它们的 id 访问元素,然后获取值并最后检查它们是否有效:

function member() {
    // Get the elements
    var user_input = document.getElementById("txtuser");
    var pass_input = document.getElementById("txtpass");

    // Get their values
    var user_value = user_input.value;
    var pass_value = pass_input.value;

    // Validate values, this is up to you
    if ( /* this is your homework */ ) {
        // Here values are OK, save a cookie with the username
        saveTheCookie(user_value);
        return true; // Form is OK
    }
    else {
        // Form is wrong
        return false;
    }
}

您可以使用以下功能存储 cookie:

function saveTheCookie(value) {
    var today = new Date(); // Actual date
    var expire = new Date(); // Expiration of the cookie

    var cookie_name = "username_form"; // Name for the cookie to be recognized
    var number_of_days = 10; // Number of days for the cookie to be valid (10 in this case)

    expire.setTime( today.getTime() + 60 * 60 * 1000 * 24 * number_of_days ); // Current time + (60 sec * 60 min * 1000 milisecs * 24 hours * number_of_days)

    document.cookie = cookie_name + "=" + escape(value) + "; expires=" + expire.toGMTString();
}

要获取 cookie 的值:

function getTheCookie() {
    var cookie_name = "username_form";
    var return_value = null;

    var pos_start = document.cookie.indexOf(" " + cookie_name + "=");
    if (pos_start == -1) document.cookie.indexOf(cookie_name + "=");

    if (pos_start != -1) { // Cookie already set, read it
        pos_start++; // Start reading 1 character after
        var pos_end = document.cookie.indexOf(";", pos_start); // Find ";" after the start position

        if (pos_end == -1) pos_end = document.cookie.length;
        return_value = unescape( document.cookie.substring(pos_start, pos_end) );
    }

    return return_value; // null if cookie doesn't exist, string otherwise
}

请注意,我没有对此进行测试,这是您开始的一个想法。您仍然必须检查表单,设置 cookie 并在加载页面时检索它(包括在标记中的onload事件中设置 DOM 元素的 HTML)。body祝你好运!

于 2013-05-25T04:48:41.473 回答