Pregunta

<ul class="messagesList ifClicked">
           <script id="questionsTemplate" type="text/x-jquery-tmpl">  
                   <li>
                      <span class="from">${source} </span>
                   </li>
             </script>
</ul>

I have the above jquery template code. The expected output by me is like

<ul class="messagesList ifClicked">
                   <li>
                      <span class="from">Reuters</span>
                   </li>                   
                   <li>
                      <span class="from">CNN</span>
                   </li>
                   <li>
                      <span class="from">CNN</span>
                   </li>
</ul>

But what is coming is (While looking in firebug)

<ul class="messagesList ifClicked">
           <script id="questionsTemplate" type="text/x-jquery-tmpl">  
                   <li>
                      <span class="from">${source} </span>
                   </li>
             </script>
</ul>
                       <li>
                          <span class="from">Reuters</span>
                       </li>                   
                       <li>
                          <span class="from">CNN</span>
                       </li>
                       <li>
                          <span class="from">CNN</span>
                       </li>

What is the reason for the behavior ?

¿Fue útil?

Solución

I would move the template outside of ul list. That way you can simply empty the list if you want to reset it.

HTML:

<script id="questionsTemplate" type="text/x-jquery-tmpl">  
        <span class="from">${source} </span>
</script>

<ul class="messagesList ifClicked">

</ul>

JS:

$(document).ready(function(){

    var list = [ 'Routers', 'CNN', 'CNN' ];

    var tmpl = '';
    $.each(list, function(num, el) {
        tmpl =  $('<li>').html($('#questionsTemplate').html());
        tmpl.find('.from').html(el);
        $('.messagesList').append(tmpl);
    });

});

DEMO and CODE

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top