찾다
웹 프론트엔드JS 튜토리얼JavaScript는 사용자 이름과 로그인 비밀번호를 기억합니다(두 가지 방법)_javascript 기술

다음은 주로 자바스크립트를 사용하여 코드를 통해 사용자 이름과 로그인 비밀번호를 기억하는 방법을 보여줍니다. 구체적인 코드 내용은 아래를 참조하세요.

첫 번째 방법:

콘텐츠
로그인.html
Welcome.html
쿠키.js
common.js

login.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>login</title>
<script type="text/javascript" src="cookie.js"></script>
<script type="text/javascript" src="common.js"></script>
</head>
<body>
<form action="">
<p>
  <span>UserName:</span>
  <input id="userName" type="text" value=""/></p>
<p>
  <span>Password:</span>
  <input id="password" type="password" value=""/></p>
<p>
  <span style="font-size:12px; color:blue;">记住密码</span>
  <input id="saveCookie" type="checkbox" value="" /></p>
<p>
  <input id="submit" type="button" value="GO" />
</p>
</form>
</body>
</html>

welcome.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>welcome</title>
</head>
<body>
<h1 id="Welcome">Welcome!</h1>
<a href="login.html">点击返回登陆框</a>
</body>
</html>
cookie.js
//新建cookie。
//hours为空字符串时,cookie的生存期至浏览器会话结束。hours为数字0时,建立的是一个失效的cookie,这个cookie会覆盖已经建立过的同名、同path的cookie(如果这个cookie存在)。
function setCookie(name,value,hours,path){
  var name = escape(name);
  var value = escape(value);
  var expires = new Date();
   expires.setTime(expires.getTime() + hours*3600000);
   path = path == "" &#63; "" : ";path=" + path;
   _expires = (typeof hours) == "string" &#63; "" : ";expires=" + expires.toUTCString();
   document.cookie = name + "=" + value + _expires + path;
}
//获取cookie值
function getCookieValue(name){
  var name = escape(name);
  //读cookie属性,这将返回文档的所有cookie
  var allcookies = document.cookie;    
  //查找名为name的cookie的开始位置
   name += "=";
  var pos = allcookies.indexOf(name);  
  //如果找到了具有该名字的cookie,那么提取并使用它的值
  if (pos != -1){                       //如果pos值为-1则说明搜索"version="失败
    var start = pos + name.length;         //cookie值开始的位置
    var end = allcookies.indexOf(";",start);    //从cookie值开始的位置起搜索第一个";"的位置,即cookie值结尾的位置
    if (end == -1) end = allcookies.length;    //如果end值为-1说明cookie列表里只有一个cookie
    var value = allcookies.substring(start,end); //提取cookie的值
    return (value);              //对它解码   
     }  
  else return "";                //搜索失败,返回空字符串
}
//删除cookie
function deleteCookie(name,path){
  var name = escape(name);
  var expires = new Date(0);
   path = path == "" &#63; "" : ";path=" + path;
   document.cookie = name + "="+ ";expires=" + expires.toUTCString() + path;
}

common.js

function $(objStr){return document.getElementByIdx_x_x(objStr);}
window.onload = function(){
  //分析cookie值,显示上次的登陆信息
  var userNameValue = getCookieValue("userName");
   $("userName").value = userNameValue;
  var passwordValue = getCookieValue("password");
   $("password").value = passwordValue;  
  //写入点击事件
   $("submit").onclick = function()
   {
    var userNameValue = $("userName").value;
    var passwordValue = $("password").value;
    //服务器验证(模拟)  
    var isAdmin = userNameValue == "admin" && passwordValue =="123456";
    var isUserA = userNameValue == "userA" && passwordValue =="userA";
    var isMatched = isAdmin || isUserA;
    if(isMatched){
      if( $("saveCookie").checked){ 
         setCookie("userName",$("userName").value,24,"/");
         setCookie("password",$("password").value,24,"/");
       }  
       alert("登陆成功,欢迎你," + userNameValue + "!");
       self.location.replace("welcome.html");
     }
    else alert("用户名或密码错误,请重新输入!");  
   }
}

두 번째 방법:

<script type="text/javascript">
window.onload=function onLoginLoaded() {
if(isPostBack == "False") {
GetLastUser();
}
}
function GetLastUser() {
var id = "49BAC005-7D5B-4231-8CEA-16939BEACD67";//GUID标识符
var usr = GetCookie(id);
if (usr != null) {
document.getElementById('txtUserName').value = usr;
} 
else {
document.getElementById('txtUserName').value = "001";
}
GetPwdAndChk();
}
//点击登录时触发客户端事件
function SetPwdAndChk() {
//取用户名
var usr = document.getElementById('txtUserName').value;
alert(usr);
//将最后一个用户信息写入到Cookie
SetLastUser(usr);
//如果记住密码选项被选中
if(document.getElementById('chkRememberPwd').checked == true) {
//取密码值
var pwd = document.getElementById('txtPassword').value;
alert(pwd);
var expdate = new Date();
expdate.setTime(expdate.getTime() + 14 * (24 * 60 * 60 * 1000));
//将用户名和密码写入到Cookie
SetCookie(usr, pwd, expdate);
} 
else {
//如果没有选中记住密码,则立即过期
ResetCookie();
}
}
function SetLastUser(usr) {
var id = "49BAC005-7D5B-4231-8CEA-16939BEACD67";
var expdate = new Date();
//当前时间加上两周的时间
expdate.setTime(expdate.getTime() + 14 * (24 * 60 * 60 * 1000));
SetCookie(id, usr, expdate);
}
//用户名失去焦点时调用该方法
function GetPwdAndChk() {
var usr = document.getElementById('txtUserName').value;
var pwd = GetCookie(usr);
if (pwd != null) {
document.getElementById('chkRememberPwd').checked = true;
document.getElementById('txtPassword').value = pwd;
} 
else {
document.getElementById('chkRememberPwd').checked = false;
document.getElementById('txtPassword').value = "";
}
}
//取Cookie的值
function GetCookie(name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
//alert(j);
if (document.cookie.substring(i, j) == arg) return getCookieVal(j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
var isPostBack = "<%= IsPostBack %>";
function getCookieVal(offset) {
var endstr = document.cookie.indexOf(";", offset);
if (endstr == -1) endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
//写入到Cookie
function SetCookie(name, value, expires) {
var argv = SetCookie.arguments;
//本例中length = 3
var argc = SetCookie.arguments.length;
var expires = (argc > 2) &#63; argv[2] : null;
var path = (argc > 3) &#63; argv[3] : null;
var domain = (argc > 4) &#63; argv[4] : null;
var secure = (argc > 5) &#63; argv[5] : false;
document.cookie = name + "=" + escape(value) + ((expires == null) &#63; "" : ("; expires=" + expires.toGMTString())) + ((path == null) &#63; "" : ("; path=" + path)) + ((domain == null) &#63; "" : ("; domain=" + domain)) + ((secure == true) &#63; "; secure" : "");
}
function ResetCookie() {
var usr = document.getElementById('txtUserName').value;
var expdate = new Date();
SetCookie(usr, null, expdate);
}
</script>
</head>
<body>
<form id="form1">
<div> 
用户名:<input type="text" ID="txtUserName" onblur="GetPwdAndChk()">
<input type="password" ID="txtPassword">
密码:
<input type="checkbox" ID="chkRememberPwd" />
记住密码
<input type="button" OnClick="SetPwdAndChk()" value="进入"/>
</div>
</form>
</body>

위는 JavaScript를 사용하여 사용자 이름과 로그인 비밀번호를 두 가지 방법으로 기억하는 전체 코드입니다. 실행 중인 렌더링을 정리할 시간이 없었습니다.

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
JavaScript로 문자열 문자를 교체하십시오JavaScript로 문자열 문자를 교체하십시오Mar 11, 2025 am 12:07 AM

JavaScript 문자열 교체 방법 및 FAQ에 대한 자세한 설명 이 기사는 JavaScript에서 문자열 문자를 대체하는 두 가지 방법 인 내부 JavaScript 코드와 웹 페이지의 내부 HTML을 탐색합니다. JavaScript 코드 내부의 문자열을 교체하십시오 가장 직접적인 방법은 대체 () 메소드를 사용하는 것입니다. str = str.replace ( "find", "replace"); 이 메소드는 첫 번째 일치 만 대체합니다. 모든 경기를 교체하려면 정규 표현식을 사용하고 전역 플래그 g를 추가하십시오. str = str.replace (/fi

jQuery 날짜가 유효한지 확인하십시오jQuery 날짜가 유효한지 확인하십시오Mar 01, 2025 am 08:51 AM

간단한 자바 스크립트 함수는 날짜가 유효한지 확인하는 데 사용됩니다. 기능 isValidDate (s) { var 비트 = s.split ( '/'); var d = 새로운 날짜 (비트 [2]/'비트 [1]/'비트 [0]); return !! (d && (d.getmonth () 1) == 비트 [1] && d.getDate () == 숫자 (비트 [0]); } //시험 var

jQuery는 요소 패딩/마진을 얻습니다jQuery는 요소 패딩/마진을 얻습니다Mar 01, 2025 am 08:53 AM

이 기사에서는 jQuery를 사용하여 DOM 요소의 내부 마진 및 마진 값, 특히 요소의 외부 마진 및 내부 마진의 특정 위치를 얻고 설정하는 방법에 대해 설명합니다. CSS를 사용하여 요소의 내부 및 외부 마진을 설정할 수는 있지만 정확한 값을 얻는 것이 까다로울 수 있습니다. // 설정 $ ( "div.header"). css ( "margin", "10px"); $ ( "Div.Header"). CSS ( "패딩", "10px"); 이 코드는 생각할 수 있습니다

10 JQuery Accordions 탭10 JQuery Accordions 탭Mar 01, 2025 am 01:34 AM

이 기사는 10 개의 탁월한 jQuery 탭과 아코디언을 탐구합니다. 탭과 아코디언의 주요 차이점은 콘텐츠 패널이 표시되고 숨겨진 방식에 있습니다. 이 10 가지 예를 살펴 보겠습니다. 관련 기사 : 10 JQuery Tab 플러그인

10 JQuery 플러그인을 확인할 가치가 있습니다10 JQuery 플러그인을 확인할 가치가 있습니다Mar 01, 2025 am 01:29 AM

웹 사이트의 역학 및 시각적 매력을 높이기 위해 10 개의 탁월한 jQuery 플러그인을 발견하십시오! 이 선별 된 컬렉션은 이미지 애니메이션에서 대화식 갤러리에 이르기까지 다양한 기능을 제공합니다. 이 강력한 도구를 탐색합시다. 관련 게시물 : 1

노드 및 HTTP 콘솔로 HTTP 디버깅노드 및 HTTP 콘솔로 HTTP 디버깅Mar 01, 2025 am 01:37 AM

HTTP-Console은 HTTP 명령을 실행하기위한 명령 줄 인터페이스를 제공하는 노드 모듈입니다. 웹 서버, 웹 서비스에 대해 만들어 졌는지 여부에 관계없이 HTTP 요청과 함께 어떻게 진행되고 있는지 정확하게 보는 데 유용합니다.

사용자 정의 Google 검색 API 설정 자습서사용자 정의 Google 검색 API 설정 자습서Mar 04, 2025 am 01:06 AM

이 튜토리얼은 사용자 정의 Google 검색 API를 블로그 또는 웹 사이트에 통합하는 방법을 보여 주며 표준 WordPress 테마 검색 기능보다보다 세련된 검색 경험을 제공합니다. 놀랍게도 쉽습니다! 검색을 Y로 제한 할 수 있습니다

jQuery div에 스크롤 바를 추가합니다jQuery div에 스크롤 바를 추가합니다Mar 01, 2025 am 01:30 AM

다음 jQuery 코드 스 니펫은 DIV 내용이 컨테이너 요소 영역을 초과 할 때 스크롤 바를 추가하는 데 사용될 수 있습니다. (데모 없음, FireBug에 직접 복사하십시오) // d = 문서 // w = 창 // $ = jQuery var contentArea = $ (this), wintop = contentArea.scrolltop (), docheight = $ (d) .height (), winheight = $ (w) .height (), divheight = $ ( '#c

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구