localStorage.getItem检索“ null”

时间:2018-08-05 18:46:15

标签: javascript html

我试图获取一个按下按钮的次数的计数器,但是当我尝试在函数外部检索它时,它将导致返回“ 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;

4 个答案:

答案 0 :(得分:1)

使您的代码多一点,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上找到此代码的示例(由于堆栈溢出不支持本地存储,因此无法找到它)

现在,我唯一真正担心的是HTML的文本,请注意localStorage将是所有客户端的个人存储,因此,如果这是一个通过互联网运行的网站,则所有到达一次将以null(或0)开头,并且每次单击该按钮时仅增加1,您将是明智之选,因为它是localStorage。

当然,如果您在一台计算机上处​​理数据,人们必须在该计算机上输入数据,那么您至少在本地存储了一些数据,但是,这并不是真正的存储,您可以使用;)做些什么>

答案 1 :(得分:0)

该代码确实有效。但是,必须确保在加载页面之前已对counter函数进行了解释。将JS放在文档head的末尾,或使用addEventListener重写onlick。

答案 2 :(得分:0)

您应该转换为整数..

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;

请重试

答案 3 :(得分:0)

getItem/setItem 在 didFinish 执行之前不可用,除非 Read local storage data using WKWebView