Reputation: 5
I didn't want to repeat the same code 25 times in the part of "getElementById", "carregaItem(iVid)" and " < div id="item"> < /div> ". The BDVYT array has 25 elements I just put 2 for simplicity. There must be some way to do it but I'm not getting there.
var BDVYT = [{durac:27},{durac:23},];
refItem = document.getElementById("item");
refItem2 = document.getElementById("item2");
function inic(){
mostraItem();
}
function mostraItem(){
carregaItem(0);
carregaItem1(1);
//-----------
//until carregaItem24(24)
}
function carregaItem(iVid){
var codHTML = "";
codHTML += '<div id="itemInfo">';
codHTML += 'duração: <b>' + duracVid(iVid) + 'minutos</b>';
codHTML += '</div>';
refItem.innerHTML = codHTML;
}
function carregaItem1(iVid){
var codHTML = "";
codHTML += '<div id="itemInfo2">';
codHTML += 'duração: <b>' + duracVid(iVid) + 'minutos</b>';
codHTML += '</div>';
refItem2.innerHTML = codHTML;
}
//until carregaItem24(iVid)
function duracVid(iVid){
return BDVYT[iVid].durac;
}
<body onload="inic()">
<div id="item"></div>
<div id="item2"></div>
</body>
Upvotes: 0
Views: 58
Reputation: 370729
Use classes for the refItem
s instead, and when iterating over the collection of them, use the index being iterated over to find the associated element in the BDVYT
array.
var BDVYT = [{durac:27},{durac:23},];
const refItems = document.querySelectorAll('.item');
refItems.forEach((item, i) => {
item.innerHTML = `
<div id="itemInfo2">
duração: <b>${BDVYT[i].durac} minutos</b>
</div>
`;
});
<body>
<div class="item"></div>
<div class="item"></div>
</body>
Upvotes: 2