简体   繁体   English

如何在 cookie 中存储运行总计(使用 javascript 或 jquery)

[英]How to store a running total in a cookie (using javascript or jquery)

I have a series of different divs on a page each with two buttons, one which I would like to add 1 to the running total and one which subtracts 1 from the running total when clicked.我在一个页面上有一系列不同的 div,每个 div 有两个按钮,一个我想在运行总数中加 1,另一个在单击时从运行总数中减去 1。

I know that this piece of jquery will set the cookie for div1 to 1, but how do I add and subttract to this total?我知道这块 jquery 会将 div1 的 cookie 设置为 1,但是我如何添加和减去这个总数?

   $('.div1').click(function() {
   $.cookie('div1', '1');
});

Also, on a related note, is it possible to store all of this data for every div on the page in a single cookie.此外,在相关说明中,是否可以将页面上每个 div 的所有这些数据存储在单个 cookie 中。 It seems inefficient to have a separate cookie tracking the running total for each div.有一个单独的 cookie 跟踪每个 div 的运行总数似乎效率低下。 I will be using php to access the cookie/s to use the running totals.我将使用 php 访问 cookie/s 以使用运行总计。

I would do something like this...我会做这样的事情......

  1. create a javascript object to store your running totals创建一个 javascript object 来存储您的运行总数
  2. encode your object in a string format suitable to be stored in cookie and that can easily be decoded from php (look into JSON for this)将您的 object 编码为适合存储在 cookie 中的字符串格式,并且可以很容易地从 php 解码(为此查看 JSON)
  3. when clicking buttons, add/decrement the value, before sending the data to server, encode and save as cookie单击按钮时,添加/减少值,在将数据发送到服务器之前,编码并保存为 cookie

To add or subtract to the value of the cookie you can do the following:要增加或减少 cookie 的值,您可以执行以下操作:

var value = parseInt($.cookie('div1'));

value += 1;

$.cookie('div1', value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM