猿问

计数器点击保存 Cookie

我创建了一个带有计数器显示的简单计数器按钮,但我不知道如何创建 cookie 来保存计数器。


我想保存计数器以显示给下一个用户,如果计数是“10”,当他继续投票 11


var contador = 1;

var time;

var on = false;

var seconds = 0;



function cambiar() {


  if (seconds >= 10) {

    document.getElementById('contador').innerHTML = contador + 0;

  } else {

    document.getElementById('contador').innerHTML = contador += 1;

  }


}

h1 {

  text-align: center;

  padding-top: 4em;

}


#cuadrito {

  width: 100px;

  padding: 50px;

  margin: 00px auto;

  border-radius: 10px;

  font-weight: bold;

  color: #DAA3A3;

}


#contador {

  font-size: 50px;

  font-weight: bold;

  color: #a3bad8;

}


#boton {

  width: 100px;

  height: 40px;

  border: none;

  font-weight: bold;

  color: #DAA3A3;

}

<body>

  <h1>VOTA BOX</h1>

  <div id="cuadrito">

    <center>

      <div id="contador">0</div>

    </center>

    <br>

    <input type="button" id="boton" value="+1" onClick="cambiar();">

  </div>

</body>


ibeautiful
浏览 190回答 2
2回答

FFIVE

您需要使用document.cookie = 'something'选择器来分配新的 cookie。我建议改用 HTML5 localstorage,这是一种更现代的解决方案。使用 localstorage,您可以在 localstoragewindow.localStorage.setItem('key', 'value')中设置一个值并window.localStorage.getItem('key')检索它。请注意,由于片段的性质,它无法在下面的片段中正常工作。// we retrieve the data from the localstorage, or we default back to 1.var contador = window.localStorage.getItem('count') || 1;var time;&nbsp;var on = false;var seconds = 0;function cambiar(){&nbsp;&nbsp;&nbsp; if(seconds >= 10){&nbsp; &nbsp; document.getElementById('contador').innerHTML = contador + 0;&nbsp; }else{&nbsp; &nbsp; document.getElementById('contador').innerHTML = contador += 1;&nbsp; }&nbsp;&nbsp;&nbsp; // we save the count value into the localstorage.&nbsp; window.localStorage.setItem('count', contador);}h1 {&nbsp; text-align: center;&nbsp; padding-top: 4em;}#cuadrito{&nbsp; width:100px;&nbsp; padding:50px;&nbsp; margin:00px auto;&nbsp; border-radius:10px;&nbsp; font-weight: bold;&nbsp; color: #DAA3A3;}#contador{&nbsp; &nbsp; font-size: 50px;&nbsp; font-weight: bold;&nbsp; color: #a3bad8;}#boton{&nbsp; width:100px;&nbsp; height:40px;&nbsp; border:none;&nbsp; font-weight: bold;&nbsp; color: #DAA3A3;}<body>&nbsp; &nbsp; <h1>VOTA BOX</h1>&nbsp; &nbsp; <div id="cuadrito"><center>&nbsp; &nbsp; &nbsp; &nbsp; <div id="contador">0</div></center>&nbsp; &nbsp; &nbsp; &nbsp; <br>&nbsp; &nbsp; &nbsp; &nbsp; <input type="button" id="boton" value="+1" onClick="cambiar();">&nbsp; &nbsp; </div></body>

梵蒂冈之花

您可以localStorage像这样保存它:-// set counter keylocalStorage.setItem('counter', 10);// get counter keyvar counter = localStorage.getItem('counter');
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答