简体   繁体   中英

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.

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?

   $('.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. It seems inefficient to have a separate cookie tracking the running total for each div. I will be using php to access the cookie/s to use the running totals.

I would do something like this...

  1. create a javascript object to store your running totals
  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)
  3. when clicking buttons, add/decrement the value, before sending the data to server, encode and save as cookie

To add or subtract to the value of the cookie you can do the following:

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

value += 1;

$.cookie('div1', value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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