An example of how to go through a sequence of IDs.
The magic starts at this point list = $('[id^=foo]');
.
With this, you get an array of objects whose ID starts with "foo".
With the array in hand, just play with the information and automate all other processes related to the number that makes up the ID.
The example below is just a toggle (). Change it for the actions you want to implement.
The code is simple and I tried to put something generic and similar to the code of the question.
$().ready(function() {
/**
Procura todos os IDS que começam com "foo".
*/
list = $('[id^=foo]');
/**
Verifica o tamanho do array. Se for maior que ZERO, indica que encontrou objetos.
*/
if(list.length > 0){
/**
Laço de repetição para iterar o array. Equivalente ao foreach() do PHP.
*/
$.each(list, function(key, row) {
/**
Extrai o número do ID
*/
num = row.id.replace(/\D/g, '');
/**
Imprime os resultados no console.
No Google Chrome, pressione CTRL+SHIT+I para ver o console.
*/
console.log('key: '+key+', id: '+row.id, num);
$('#bar'+num).click(function() {
/**
Extrai o número do ID
*/
num = this.id.replace(/\D/g, '');
/**
Exibe ou oculta o objeto relacionado com ID do objeto clicado.
*/
$('#foo'+num).toggle();
/**
Exibe o número clicado, no console.
*/
console.log(num);
});
/**
Oculta os objetos "foo".
*/
$('#'+row.id).toggle();
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="bar1">bar</div>
<div id="foo1">foo</div>
<div id="bar2">bar</div>
<div id="foo2">foo</div>
<div id="bar3">bar</div>
<div id="foo3">foo</div>
<div id="bar4">bar</div>
<div id="foo4">foo</div>
<div id="bar5">bar</div>
<div id="foo5">foo</div>
In your code it will be a bit tricky to use this logic without modifying the ID pattern of the element that receives the click.
In elements called "collapse" that receive the click () trigger, I suggest modifying it to another name like "bar_collapse" + number.
The number must be identical to the other collapse element that invokes the load () method.
Example
<div id="bar_collapse1">
<div id="collapse1"></div>
</div>
<div id="bar_collapse2">
<div id="collapse2"></div>
</div>
This is required to make it easier to search objects list = $('[id^=bar_collapse]');