简体   繁体   中英

How to wrap for loop in a div?

I have been stuck on this silly thing, I can't figure out how to wrap my for loop inside of a div.

for (item = 0; item < event.length; item++) {
        var ID = event[item].id;
        element.find(".title").after("<span class='id'><img src='/avatar/" +ID+ "'/></span>");
        }

I want to achive this:

<div>
<span></span>
<span></span>
<span></span>
</div>

Any Help is much apprciated.

Hope this snippet will be useful

// a variable for the dynamically created span
var spanString = "";
for (item = 0; item < event.length; item++) {
  var ID = event[item].id;
  // new string will con cat wit the spanString
  spanString += ("<span class='id'><img src='/avatar/" + ID + "'/></span>");
}

// append the spanString to the `div.title`
$(".title").append($(spanString))
$(document).ready(function() {  
//Assume sample event array 
var event = [1, 2, 3];
for (item = 0; item < event.length; item++) {
    var ID = event[item];
    $("<span class='id'><img src='/avatar/" +ID+ "'/></span<br>").appendTo('#name');
  };
});

Considering sample HTML Below

<div id="name">
   hello
</div>

This way you can populate content inside the div

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM