![](/img/trans.png)
[英]Why is localStorage[“…”] undefined, but localStorage.getItem(“…”) is null?
[英]localStorage.getItem retrieves 'null'
我正在嘗試獲取按下按鈕次數的計數器,但是當我嘗試在函數外部檢索它時,它會導致“空”。
HTML:
<button class="signupbutton" onclick="counter()"> Yes I'm in!</button>
<div id="counter">
<p>Number of people that have signed up for the newsletter: </p>
<div id="counter1">0</div>
</div>
Javascript:
function counter() {
var elem = document.getElementById('counter1');
var count = localStorage.getItem('count');
if (count == null) {
count = 0;
}
count++;
localStorage.setItem('count', count);
elem.innerHTML = count;
}
console.log(localStorage.getItem('count'));
var count1 = localStorage.getItem('count');
var elem = document.getElementById('counter1');
elem.innerHTML = count1;
使您的代碼更加 DRY 會為您節省一些時間,以驗證您的計數器是否具有“真實”值。 其余的,不再鼓勵 html 元素內的onclick
,您可以像這樣更新您的代碼
// wait until the page has loaded
window.addEventListener('load', function() {
// get your elements once
const counterElement = document.querySelector('#counter1');
const signupButton = document.querySelector('.signupbutton');
// assign a click event to your button
signupButton.addEventListener('click', updateCounter);
// function to retrieve the counter from your localStorage
function getKeyOrDefault( key, defaultValue = 0 ) {
return localStorage.getItem( key ) || defaultValue;
}
function updateCounter( e ) {
let counter = parseInt( getKeyOrDefault( 'counter' ) );
counter++;
counterElement.innerHTML = counter;
localStorage.setItem( 'counter', counter );
e.preventDefault();
}
// set the initial value
counterElement.innerHTML = getKeyOrDefault( 'counter' );
} );
當然,不要忘記更改您的 html,從 html 元素中刪除計數器功能,例如
<button class="signupbutton"> Yes I'm in!</button>
<div id="counter">
<p>Number of people that have signed up for the newsletter: </p>
<div id="counter1">0</div>
</div>
可以在此jsfiddle上找到此代碼的示例(它不在此處,因為 stackoverflow 不支持 localstorage)
現在,我唯一真正擔心的是你的 HTML 文本,注意 localStorage 將是所有客戶端的個人存儲,所以,如果這是一個從互聯網運行的網站,所有到達那里的人都會從 null(或 0)開始,每次點擊按鈕時只增加 1,你不會更聰明,因為它是 localStorage。
當然,如果您在一台計算機上處理它,人們必須在其中輸入數據,那么您至少會在本地存儲一些數據,但是,這仍然不是您可以使用的真正存儲;)
該代碼確實有效。 但是,您必須確保在頁面加載之前解釋counter
函數。 將 JS 放在文檔head
的末尾,或者使用addEventListener
重寫 onlick。
您應該轉換為整數..
function counter() {
var elem = document.getElementById('counter1');
var count = localStorage.getItem('count');
if (count == null) {
count = 0;
}
count = parseInt(count);
count++;
localStorage.setItem('count', count);
elem.innerHTML = count;
}
console.log(localStorage.getItem('count'));
var count1 = localStorage.getItem('count');
var elem = document.getElementById('counter1');
elem.innerHTML = count1;
請再試一次
除非使用 WKWebView 讀取本地存儲數據,否則在執行 didFinish 之前,getItem/setItem 不可用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.