Local Storage Jquery

2019-09-18 13:23发布

I'm working on local storage using jQuery. I've got an input field in which you can type some text, press enter, refresh and the text is still there. So that's working fine.

But I want to combine it with a different function I wrote. In this function a user can click on a grey button which will then "activate" it so it turns red, and it will add a 1 to the container. It's a "like button".

So how can I save the click counter information (button turning red, and value updated) using local storage?

I made this jsfiddle: http://jsfiddle.net/Yazuri/7ZxMK/

jQuery(function ($) {

  if (typeof (window.localStorage) != "undefined") {


      $("input[type=text]").val(function () {
          return localStorage.getItem(this.id);
      });

      $("input[type=text]").on("change", function () {
          localStorage.setItem(this.id, $(this).val());
      });
  }
});

3条回答
▲ chillily
2楼-- · 2019-09-18 13:57

You can store the counts from the "hearts"

Updated your Fiddle

JSFIDDLE

$(document).ready(function () {

    $('.clickheart').click(function () {
        $(this).find(".output").html(function (i, val) {
            if (val < 1) {

                $(this).addClass('heartrood');
                localStorage.setItem("hearts",  val * 1 + 1);
                return val * 1 + 1;

            } else {
                $(this).removeClass('heartrood');
                localStorage.setItem("hearts",  val * 1 - 1);
                return val * 1 - 1;
            }
        });
    });


});
查看更多
【Aperson】
3楼-- · 2019-09-18 13:59

Here is your Updated Fiddle

 $("input[type=text]").each(function(){
     $(this).val(localStorage.getItem(this.id));
 });


 $("input[type=text]").on("change", function () {

     localStorage.setItem(this.id, $(this).val());
 });

You cannot write it in this way $("input[type=text]").val(function () {}). There is not event on val.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-09-18 14:00

Demo Fiddle

  1. Retrieve and save the total number of clicks
    var result = $(".output").text(); localStorage.setItem('click', result);

  2. If the local storage exists with key click show it in the div
    if (localStorage.getItem('click') != null) { $('.output').text(localStorage.getItem('click')); }

Hope it helps...!!

查看更多
登录 后发表回答