Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

html - Javascript - Creating divs to a foreach loop every x times

I have a foreach loop and I need to wrap a div with className='row' around the output of the data every 2 loops.

this is my loop

function getUsers(){
usersjson.users.forEach(function (user,counter) {
//create a DOM element
var div = document.createElement('div');
//add class row every 2 loops
div.className = 'row';
//names
var names = "<p>" + user.first_name +' '+user.last_name+"</p>";
//append to html
div.innerHTML = names;
$('.users_list').append(div);
});
}

This is how it should look like

<div class="row">
<p>John Doe</p>
<p>Jane Doe</p>
</div>

<div class="row">
<p>Marcy Doe</p>
<p>Alfred Doe</p>
</div>

<div class="row">
<p>Judy Doe</p>
<p>Lana Doe</p>
</div>

//...etc
question from:https://stackoverflow.com/questions/65622857/javascript-creating-divs-to-a-foreach-loop-every-x-times

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Can you try this:

function getUsers(){

    let names = ""
    usersjson.users.forEach(function (user,counter) {

        names = names + "<p>" + user.first_name +' '+user.last_name+"</p>";
        if(counter % 2  == 0) {
            $('.users_list').append(`<div class="row">${names}</div>`);
            names = ""
        } 

    });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...