如何将点击事件保存在本地存储中

时间:2019-05-21 09:05:15

标签: javascript jquery local-storage

我想创建一个通知铃声小部件,该小部件可提取所有带有标签theBell标记的文章。

当用户单击打开包含此文章的列表的图标时,通知计数和click事件应保存在本地存储中,这样,当用户刷新页面时,浏览器就会知道这些文章已被“阅读”(就我而言,该图标已被点击)。

我的问题是如何捕获该点击事件并将其保存到本地存储中?

$.each(data.articles, function(index, item) {
  var style1 = '<li class = "eagle"><a href="' + item.html_url + '">' + item.title + '</a><span class = "eagleClose">x</span></li>'

  $('#notificationTab').append(style1);
  $('#notificationTab').each(function() {
    var str = document.getElementById("notificationTab").innerHTML;
    var res = str.replace(/null/g, ' ');
    document.getElementById("notificationTab").innerHTML = res;

    //count how many list items there are and display them in the tomato
    var tabLength = $('#notificationTab .eagle').length;
    $('.notificationCount').text(tabLength);

    //remove notificationCount when bell is clicked
    var removeTomato = $('.notificationTrigger').on('click', function() {
      $('.notificationCount').remove();
    });
  });
});

1 个答案:

答案 0 :(得分:0)

在代码中将相关行替换为这些行,

//count how many list items there are and display them in the tomato
var tabLength = $('#notificationTab .eagle').length;
if (localStorage.hasOwnProperty('notificationCountViewed') && localStorage.getItem('notificationCountViewed')) {
     $('.notificationCount').text();
} else {
     $('.notificationCount').text(tabLength);
}

还有这个:

//remove notificationCount when bell is clicked
var removeTomato = $('.notificationTrigger').on('click', function() {
  $('.notificationCount').remove();
  localStorage.setItem('notificationCountViewed', true);
});