每个项目

时间:2018-01-13 13:28:08

标签: javascript jquery html5 local-storage

此代码在1 number中保存localstorage以及生成号码的时间,1分钟后,该项目在localstorage中更改并以htm显示。

我正在寻找一种方法,为每个带ID的项目生成1个数字

示例:

<div id="now">1 now</div>
<div id="now">5 now</div>
<div id="now">8 now</div>

此刻它就像这样显示

<div id="now">1 now</div>
<div id="now">1 now</div>
<div id="now">1 now</div>

我的代码

 <div id="now"></div>
function hasOneDayPassed() {
  var lastclear = localStorage.getItem('lastclear'),
    now_p = localStorage.getItem('now_p'),
    time_now = (new Date()).getTime();

  if ((time_now - lastclear) > 1000 * 60) {
    localStorage.clear();
    localStorage.setItem('lastclear', time_now);
    localStorage.setItem('now_p', Math.floor(Math.random() * 20) + 4);
  }
  $('#now').text(now_p + ' now');
}
hasOneDayPassed();

2 个答案:

答案 0 :(得分:1)

您可以使用jQuery .each()函数浏览类名为.now-people的所有元素。请注意,我说class,因为您不能拥有多个具有相同id的元素,而您可以拥有多个具有相同class的元素。

以下是一个例子:

注意:我评论了localStorage(它在SO上无法正常工作),因此我们可以测试randoms。最后,我们将array的所有值(string更改为JSON.stringify() - localStorage只能使用字符串)传递给localStorage item now_p。< / p>

&#13;
&#13;
function hasOneDayPassed()
{
    // var lastclear = localStorage.getItem('lastclear');
    
    var now_p = [];
    
    // check if localStorage item is set
    //if (localStorage.getItem('now_p') !== null)
    //{
    //     now_p = JSON.parse(localStorage.getItem('now_p'));
    //}
    
    // the values of localStorage variable now_p are in the array now_p, to use-> now_p[0], now_p[1] ,...
    
    var rand;
    var time_now = (new Date()).getTime();

/*
    if ((time_now - lastclear) > 1000 * 60)
    {
      localStorage.clear();
      localStorage.setItem('lastclear', time_now);
*/
      $('.now-people').each(function()
      {
          rand = Math.floor(Math.random() * 20) + 4;
          this.innerHTML = rand + ' now';
          now_p.push(this.innerHTML);
      });
/*    
      localStorage.setItem('now_p', JSON.stringify(now_p));
    }
*/

// example of mamnaging data input from localStorage
var testJSON = JSON.parse( JSON.stringify(now_p) );
// example output
console.log(testJSON);
console.log(testJSON[1]);
}

hasOneDayPassed();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="now-people">1 now</div>
<div class="now-people">5 now</div>
<div class="now-people">8 now</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我认为你必须使用不同的id,因为如果你打电话

$('#now-people').text(now_p + ' now');

您将使用id now-people覆盖每个div。