【问题标题】:How do I persist data in a local html file meme award webpage to allow the counter to persist permanently?如何在本地 html 文件 meme 奖励网页中保留数据以允许计数器永久保留?
【发布时间】:2018-08-07 05:38:34
【问题描述】:

我最近做了一个网站,它使用基本的 javascript 来制作计数器(以及 html 和 CSS 来制作图形),现在我想包含一个组件,即使页面被刷新,也可以让计数器上升。 这是一个大型项目,它将允许人们在免费代码营地球 Facebook 群组中对表情包进行投票,并将防止人们一直在网站上充斥表情包 - 这是免费代码营 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)

这是一个使用本地存储的示例和一个有效的示例! (见下文,但您必须将信息复制并粘贴到记事本中) 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.如果我能用计数器做到这一点(也许我不能......在这种情况下,任何与流行的 meme 网站合作的人可能也想知道不要尝试这样做)

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

我自己的例子是这样的:

localstorage.setitem(0, ++)

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

【问题讨论】:

  • 本地存储的 MDN 网站没有显示为链接,我不知道为什么,所以这里是链接:developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage 此评论有助于澄清我上面的链接。
  • 你应该清理代码块,只显示与问题相关的部分。 (即javascript)。大多数人只会 tldr
  • 我把它加粗了,这样您就可以查看相关的内容并略过不相关的内容,因为我知道每个人都已经很忙了。上下文中需要所有信息,否则我会被告知我不够具体。

标签: javascript html cookies local-storage counter


【解决方案1】:

如果您要保存的数据必须在网站用户之间共享,那么没有某种类型的服务器端技术是不可能的。最容易学习和设置的可能是 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,您可以在其中了解更多关于cookies的信息。

【讨论】:

  • 正是这个。如果您希望所有用户看到完全相同的计数器并在所有用户之间共享其计数,则需要使用服务器端编程语言并将计数存储在某个数据库中。如果没有,你可以使用 localStorage。
  • 你会推荐使用本地开发环境,比如 WAMP 吗?然后我就可以使用cookies了?
  • 这里是 WAMP 的链接,因此您可以获得更多信息:wampserver.com(我可能会使用的更多上下文)
  • Wamp 是一个 Web 服务器,可以执行诸如编译 PHP 之类的工作,但 cookie 是内置在浏览器中的东西,因此您可以在没有 WAMP 或任何 Web 服务器的情况下使用 cookie。就我个人而言,如果我正在做一个像这样的小网站,如果我无法访问服务器端技术,我就不会使用 Wamp 并仅通过文件访问。
猜你喜欢
  • 1970-01-01
  • 2016-09-23
  • 2022-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-17
相关资源
最近更新 更多