Pepe
Pepe

Reputation: 1002

Add new value to variable on every new function run without losing the old ones (jQuery)

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
});

Upvotes: 1

Views: 105

Answers (1)

epascarello
epascarello

Reputation: 207527

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);
});

Upvotes: 2

Related Questions