Home > Back-end >  Add new value to variable on every new function run without losing the old ones (jQuery)
Add new value to variable on every new function run without losing the old ones (jQuery)

Time:10-06

Is there a way to add a variable to the existing ones at every new function run, without losing the old ones?

Function example:

// this div value gets changes by an other click event
<div class="data">204</div>

$(".button").on('click', function(){
  var data = $('.data').text();
  var dataCollection = data   data; //   new data, the old ones should not be deleted
  console.log(dataCollection); // here I wanna see a list of all data
});

CodePudding user response:

Do not redefine the variable each time. What you are doing would make more sense as an array.

var dataCollection = [];
$(".button").on('click', function(){
  var data = $('.data').text();
  dataCollection.push(data)
  console.log(dataCollection);
});
  • Related