简体   繁体   中英

Append <div> using jquery's forEach and templatePlugin

I'm struggeling for some hours with the following problem:

  1. Iterating through a object using jquery's forEach method
  2. For each object element, a template should be used, which also fills the information in the template. The plugin, which I am using: jquery-tempalte
  3. For each object the template should be appended to a <div>

Unfortunately only the last object element is visualized and loaded to the DOM. All other divs, which are created during the steps before, were overwritten.

Find here an jsFiddle, which demonstrates my problem: http://jsfiddle.net/7oq053od/1/

Do you have any idea, what I am missing?
Would be great to get some feedback :)

For appending multiple div's . you should create a main container that contains all the child div's and when displaying, each div element will be created and append to main container everytime. Here's a sample code:

<div id="container"></div> 

//now in javascript create child div elements and append to main container
<script>

for(var items in data)
{
  var newChild = $(document.createElement('div'));  
    $(newChild).css({
    //some css code
    });
 //now appending it to main container
$('#container').append(newChild);
}

</script>

It seems the template plugin applies the templated values to the same element. If you clone the element, your script works.

$.each(results.features, function (key, value) {
    $("#homeView").clone().loadTemplate($("#template"), {
        geoFenceName: value.attributes.title,
        geoFenceDescription: value.attributes.description
    }).appendTo('#fences');
});

See updated fiddle here

From Options section on the github webpage you can see this third parameter with the append property set as true . Just consider add it to your script like this :

$.each(results.features, function (key, value) {
    $("#homeView").loadTemplate($("#template"), {
        geoFenceName: value.attributes.title,
        geoFenceDescription: value.attributes.description
    }, {append: true});
});

Here is a working JsFiddle .

The problem is that the loadTemplate function overwrites the div. You can fix that by cloning the template container and then append it to '#homeWiew'.

I created a fork from your jsfiddle that worked for me:

http://jsfiddle.net/6ksdnejw/

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