簡體   English   中英

HTML5本地存儲未存儲密碼框中的值

[英]HTML5 Local Storage not storing value from password box

我已經寫了一個HTML文件,它包含兩個輸入框,一個叫做用戶名,另一個叫做密碼。 像這樣:

<input class='registerinput' id='registerusername' placeholder='Username'></input>
<input class='registerinput' id='registerpassword' placeholder='Password' type='password'></input>
<input class='registerinput' id='registerpasswordrepeat' placeholder='Repeat Password' type='password'></input>

我想使用這些代碼將其存儲到本地存儲中。

if (document.getElementById('registerusername').value != "") {
    localStorage.username=document.getElementById('registerusername').value }
else if (document.getElementById('registerusername').value == "") {
    alert('You must enter a username.') } 
if (document.getElementById('registerpassword').value != "" && document.getElementById('registerpasswordrepeat').value == document.getElementById('registerpassword').value) {
    localStorage.password==document.getElementById('registerpassword'.value) }
else if (document.getElementById('registerpassword').value == "") {
    alert('You must enter a password') }
if (document.getElementById('registerpasswordrepeat').value != document.getElementById('registerpassword').value) {
    alert('The password did not match.') } 

一切正常,除了我無法將值保存在密碼框中。 是出於安全性的HTML5存儲限制還是我的代碼中的錯誤? 謝謝。

在回答之前,請注意,有些瀏覽器可能不支持此功能,您可以通過以下方式檢測到它:

if(window.localStorage) {
    // do your local storage stuff here
} else {
    // do something else instead as localStorage is not available
}

除了這些信息,這是您的錯字:

localStorage.password==document.getElementById('registerpassword'.value) }

結束'后,您缺少括號。

正如jmort253指出的那樣,即使幾乎所有瀏覽器都支持localStorage ,檢查瀏覽器的支持也是明智的選擇(但真正需要使用您的應用程序的瀏覽器才不是。)。

並更改此行(在錯誤的位置加double =和右括號):

localStorage.password==document.getElementById('registerpassword'.value)

至:

localStorage.password = document.getElementById('registerpassword').value;

但是, localStorage更“正確”的語法是使用:

localStorage.setItem(key, value);

您使用以下方法檢索:

var value = localStorage.getItem(key);

這將為您提供Stringnull如果不存在,則直接屬性方式將始終提供undefined如果key不存在)。

避免出現此類錯誤的另一個技巧是集中變量,例如:

var password1 = document.getElementById('registerpassword').value,
    password2 = document.getElementById('registerpasswordrepeat').value;

if (password1.length > 0 && password1 === password2) { ... }

這樣,您就可以更輕松地發現是否發生錯誤(而且,這樣做還快一點)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM