How to differentiate localStorage from storing each file on click?

前端 未结 2 1817
南旧
南旧 2020-12-21 01:21

I\'ve made a simple jQuery script which stores values \"voted1\", \"voted2\", \"voted3\" in localStorage. The problem is

相关标签:
2条回答
  • 2020-12-21 02:02
      $(document).ready(function() {
        var voteLink = $(".gallery-item a");
        var votedYes = $(".exists");
        if (localStorage.getItem("count") === null) {
          localStorage.setItem("count", 1)
        }
        if (!(localStorage.getItem("voted3") === "yes3")) {
          var i = Number(localStorage.getItem("count")),
            fn = function(e) {
              if (i < 3) {
                localStorage.setItem("voted" + i, "yes" + i);
                $(this).text("Thank you! for vote " + i)
                  .addClass("voted" + i);
                localStorage.setItem("count", 1 + i);
                i = Number(localStorage.getItem("count"));
              } else {
                localStorage.setItem("voted" + i, "yes" + i);
                $(this).text("Thank you! for vote " + i)
                  .addClass("voted" + i)
                  .fadeOut("slow");
                if (localStorage.getItem("voted3") === "yes3") {
                  voteLink.remove();
                  votedYes.fadeIn(1800);
                }
              }
            };
          voteLink.on("click", fn);
        } else {
          // if `localStorage` has property `"voted3"` and value equals `"yes3"`, 
          // do stuff
        }
      })
    
    0 讨论(0)
  • 2020-12-21 02:06

    Caveat: This answer may be completely off, since your question comes without all the details of your use case. However ...

    The following code assumes that ...

    • up to 3 votes shall be recorded in localStorage
    • in order to cast the vote n+1, vote n must have been recorded before.

    Either register the handlers contingent on the content in localStorage:

    if (
          localStorage.getItem("voted1")
       && !localStorage.getItem("voted2")
    ) {
         voteLink.one('click', function() {
             localStorage.setItem('voted2', 'yes2');
             //...
         });
    }
    

    ... or test the localStorage contents inside your event handler:

    fn_vote2 = function() {
        if (
              localStorage.getItem("voted1")
           && !localStorage.getItem("voted2")
        ) {
            localStorage.setItem('voted2', 'yes2');
            //...
            voteLink.off('click', fn_vote2);
        }
    };
    voteLink.on('click', fn_vote2);
    

    The generalization for vote1, vote3 should come easy. Note that the latter solution implies that you register the handler not just for a single event. Instead you deregister it upon success.

    The advantage of the method is the option for cascaded voting without reloading the page.

    Btw, since localStorage persists over sessions, it is advisable not to use generic keys like vote<n>.

    0 讨论(0)
提交回复
热议问题