We have several divs with the iteam iteam , then we need to take the key from all iteam elements, then take the id values from the database, then we need to compare the id and key if they match, then display the information in the block! Everything works by the time of comparison, perhaps due to different data types! Help solve the problem
var Base = [{ id: '0', h2: 'Text1', p: 'Text2' }, { id: '1', h2: 'Text1', p: 'Text2' }, { id: '2', h2: 'Text1', p: 'Text2' } ]; //Функция добавляет Key ЕЛЕМЕНТУ function AppInitial() { $('.iteam').each(function(index) { $(this).attr('key', index); }); } AppInitial(); // function AutoBlock() { //Получаем значения key var key = $('.iteam').map(function(index) { var key = $(this).attr('key'); return key; }); //Получаем id из базы var id = Base.map(function(element) { var id = element.id; return id; }); // Base.forEach(function(element) { if (id == key) { $(".iteam h2").text(element.h2); $(".iteam p").text(element.p); } }); } AutoBlock(); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='iteam'> <h2></h2> <p></p> </div> <div class='iteam'> <h2></h2> <p></p> </div> <div class='iteam'> <h2></h2> <p></p> </div> <div class='iteam'> <h2></h2> <p></p> </div>
Array.map? w3schools.com/jsref/jsref_map.asp - Igor