javascript - 如何将数据保留在本地 html 文件 meme 奖励网页中以允许计数器永久保留?

标签 javascript html cookies local-storage counter

我最近制作了一个网站,它使用基本的 javascript 来制作计数器(以及 html 和 CSS 来制作图形),现在我想包含一个组件,即使页面刷新,计数器也可以上升。 这是一个大项目,将允许人们在免费代码营地球 Facebook 群组中对 meme 进行投票,并防止人们一直在该网站上充斥 meme - 这是 Free code Camp Sunday Funnies 社区计划的一部分。

目前,当页面刷新时,计数器会返回零。

这是至关重要的上下文,以便您可以看到我的具体问题与其他问题有多么不同! 首先,这是我的代码(同样,您需要做的就是将其发布到记事本中,我更喜欢可视化代码编辑器,因为它会自动格式化):

#Fbanner1 {
  position: absolute;
  top: 0;
  right: 0%



  }    
  #Fbanner2 {
      position: absolute;
      top: 0;
      left: 0%;


  }    
    #banner { 
       position: absolute; 
      top: 0%;
       left:0%;

}



        #hook {
            font-family: 'VT323', monospace;
            font-size: 30px;
            text-align: center;
            font-variant: small-caps;
            border-style: double solid;
            border-color:black;
            background-color:blue;
            transform: translateX(425px);

        }
        h1 {
            font-family: 'Nova Mono', monospace;
            font-size: 50px;
            text-align: center;
            transform: translateX(-5px);
        }

        body {
            background-color: green;

        }

        section {
            display: flex;
            flex-direction: row;
        }

        #main {
            font-family: 'Nova Mono', monospace;
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            justify-content: space-around;
            text-align: center;
            position: absolute;
            top: 8px;
            transform:translateY(45px);
        }

    </style>

<div id="banner">
    <div id="banner-content">
        <title>Free Code Camp Sunday Meme Award</title>
<div id="instruct"><h4 id="Hook" >!click to choose the meme of legend!</h4>
</div></div>
    </div>
 </div>
</head>
<div id="Fbanner2"><p> <img height="100" width="100" 
src=".\images\fccLogo.png" alt=""></p>     </div>
<div id="Fbanner1"><p> <img height="100" width="100" 
src=".\images\fccLogo.png" alt=""></p>     </div>
<div id="main-content">
<body>

    <div id="main">
         <div id="titleF"><h1> Sunday Funnies Meme Award </h1></div>
        <section>

            <h2> 1st place
                <figure>
                    <img src=".\images\meme1.jpg" 
onclick="incrementThumb('1st')" width=200 height=200>
                     <p id="1st">0</p>
                    <h2>
                        <figcaption> Alert: dank meme found! </figcaption>
                </figure>
                </h2>

                <h2> 2nd place
                    <figure>
                        <img src=".\images\meme1.jpg" 
onclick="incrementThumb('2nd')" width=200 height=200>
                        <p id="2nd">0</p>
                        <h2>
                            <figcaption> Getting warmer.... </figcaption>
                    </figure>
                    </h2>

                     <h2> 3rd place
                         <figure>
                             <img src=".\images\meme1.jpg" 
onclick="incrementThumb('3rd')" width=200 height=200>
                             <p id="3rd">0</p>
                            <h2>
                                <figcaption> A small ripple effect...
</figcaption>
                        </figure>
                        </h2>

                    </section>

                    <footer>                
            <h2> Honorable Mention
                <section>
                    <figure>
                        <img src=".\images\meme1.jpg" 
 onclick="incrementThumb('HM1')" width=200 height=200>
                        <p id="HM1">0</p>
                        <h2>
                            <figcaption> Worth an eyebrow raise...
</figcaption>
                    </figure>
                </section>
                </h2>
                <h2> Hononorable Mention
                    <section>
                        <figure>
                            <img src=".\images\meme1.jpg" 
onclick="incrementThumb('HM2')" width=200 height=200>
                             <p id="HM2">0</p>
                             <h2>
                                      <figcaption> Worth an eyebrow raise...
 </figcaption>
                         </figure>
                     </section>
                     </h2>
         </footer>
     </div>


            <script type="text/javascript">
                function incrementThumb(value){
                   var currentValue = 
document.getElementById(value).innerHTML; 
                   //console.log("typeof" + typeof(currentValue)); 
                    //console.log("1" + currentValue);
                   if (currentValue === undefined || currentValue === "NaN" 
|| currentValue === '') {
                       currentValue = 0;
                       //console.log("0" + currentValue);

                   }
                    //console.log("2" + currentValue);

                   var newValue = parseInt(currentValue) + 1;
                 //console.log("3" + newValue);

                   document.getElementById(value).innerHTML= newValue;
                   localStorage.setItem(newValue);} 

                function DataSaver ()


               </script>


 </body> </div></div>


</html>

我对不同的方法进行了深入研究:

How to use local storage I

how to use local storage"> How to use local storage II

conflicting information on using cookies

这是堆栈溢出中描述的类似方法,但我不知道如何将其应用于涉及计数器的具体情况: Stack overflow research confusing one about cookies in addition (or instead of?) using local storage)

Here is an example of using local storage and an example that works! (see below, but you will have to copy and paste the info into notepad) step-by-step example

MDN 本地存储指令在这种情况下没有意义:

MDN

现在您已经了解了上面的上下文,以及这是如何处理计数器变量而不是一堆数字,以及 我认为这就是我要做的,但我不知道当它从零开始并且将来会改变时如何设置该项目。下面是 Tod Motto 逐步描述的代码:

   <textarea class="localstorage"></textarea>
    <button class="clear">Clear localStorage</button>
    <button class="empty">Empty localStorage</button>
<script>
      (function () {

        // Grab the textarea
        var demo = document.querySelector('.localstorage');

        // localStorage feature detect
        function supportsLocalStorage() {
          return typeof (Storage) !== 'undefined';
         }

    // Run the detection with inverted expression
    if (!supportsLocalStorage()) {

      // Change the value to inform the user of no support
      demo.value = 'No HTML5 localStorage support, soz.';

    } else {

      // Try this
      try {

            // Set the interval and autosave every second
            setInterval(function () {
              localStorage.setItem('autosave', demo.value);
            }, 1000);

          } catch (e) {

            // If any errors, catch and alert the user
            if (e == QUOTA_EXCEEDED_ERR) {
             alert('Quota exceeded!');
            }
          }

          // If there is data available
          if (localStorage.getItem('autosave')) {

            // Retrieve the item
            demo.value = localStorage.getItem('autosave');
          }

          // Clear button, onclick handler
          document.querySelector('.clear').onclick = function () {
            demo.value = '';
            localStorage.removeItem('autosave');
          };

           // Empty button, onclick handler
          document.querySelector('.empty').onclick = function () {
            demo.value = '';
            localStorage.clear();
          };

        }

      })();
    </script>

如果您想查看问题解释的简要版本,请跳至此处

我知道我需要设置和获取信息,并且我假设该信息将是计数器,但是

A.我不知道这是否可能(如果我也需要使用cookie);网上关于不同方法的评论褒贬不一......

B.如果我需要使用WAMP(我不是问如何使用WAMP,只是如果我这样做......根据我的研究,这似乎是没有必要的)

C.如果我可以用计数器做到这一点(也许我不能......在这种情况下,任何使用流行模因网站的人可能都想知道不要尝试这样做)

D.同样重要的是,在这种情况下我应该用计数器设置什么(我正在尝试通过做项目来建立我的技能基础,这样我就可以占用你更少的时间。

我自己的例子是这样的:

localstorage.setitem(0,++)

(我之所以这么认为,是因为您每次都添加一个值。这也是断章取义,但希望可以插入到上面的 Tod Mottos 代码中。

最佳答案

如果您要保存的数据必须在网站用户之间共享,那么如果没有某种类型的服务器端技术,这是不可能的。最容易学习和设置的可能是 PHP(尽管我不喜欢它)。还有其他选择,但设置和学习语言可能很困难。

如果计数器数据对于每个用户来说都是唯一的,您可以使用 cookie 或本地存储,但它很容易被用户篡改。 Cookie 数据的设置和获取更简单,可以通过以下代码轻松完成:

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

上面的代码来自here您可以在其中了解有关 cookie 的更多信息。

关于javascript - 如何将数据保留在本地 html 文件 meme 奖励网页中以允许计数器永久保留?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49010962/

相关文章:

javascript - 引入 React 时 Webpack 无法正常工作

javascript - jQuery this.html() 返回未定义

javascript - javascript 中的硬绑定(bind)

javascript - 表单字段值在 onclick=window.print() 处刷新

php - 如何使用 span 设置 PHP 回显输出的样式

python - 如何使用 GAE/Python 设置 cookie 1 个月?

node.js - 仍然需要使用带有 passport.js 的 cookie-parser 吗?

javascript - 使用 html2canvas 设置 Png 的质量

javascript - <li> 标签在使用 mmenu 时堆叠

javascript - 如何在 JavaScript 中删除 cookie