Modifying jQuery HTML template before adding to DOM

I have a problem using the jQuery template in the same way as a regular jQuery class DOM object. I need to modify the HTML created by the template function before adding it to the DOM.
The comments in my example below explain what I want to do and what is wrong.

 <script id="movieTemplate" type="text/x-jquery-tmpl">
  <tr class="week_${week}">
   <td colspan="6">Vecka: ${week}</td>
  </tr>
  <tr class="detail">
   <td>Kund: ${customer}</td>
   <td>Projekt: ${project}</td>
   <td>Tidstyp: ${time_type}</td>
   <td>Datum: ${date}</td>
   <td>Tid: ${quantity}</td>
   <td>Beskrivning: ${description}</td>
  </tr>
 </script>


 <script type="text/javascript">
  var movies = [
    { customer: "SEMC", project: "Product catalogue", time_type: "Programmering", date: "2010-11-08", quantity: 2, description: "buggar", week: 45 },
    { customer: "SEMC", project: "Product catalogue", time_type: "Programmering", date: "2010-11-09", quantity: 3, description: "buggar igen", week: 45 }
  ];
  $("#movieTemplate").tmpl(movies).appendTo("#movieList");

  $("#btnAdd").click(function () {
   //hash with data
   var data = { customer: $("#clients").val(), project: $("#projects").val(), time_type: $("#timeTypes").val(), date: $("#date").val(), quantity: $("#quantity").val(), description: $("#description").val(), week: $("#week").val() }

   //do the templating
   var html = $("#movieTemplate").tmpl(data).find(".week_" + data.week).remove().appendTo("#movieList");
            console.log(html.html()); //Returns null. WHY?!

            var html = $("#movieTemplate").tmpl(data).appendTo("#movieList");
   console.log(html.html()); //Returns the first <tr> only. But appends the full html correctly
   return false;
  });
 </script>
+3
source share
1 answer

You add the deleted item if you want to remove the item, then add what you have left to use .end()to hop back in the chain, like this:

var html = $("#movieTemplate").tmpl(data).filter(".week_" + data.week).remove()
                                         .end().appendTo("#movieList");

.html() , .html() .

, DOM, :

var html = $("#movieTemplate").tmpl(data).appendTo("#movieList")
                              .filter(".week_" + data.week).remove();

.

+2

Source: https://habr.com/ru/post/1774281/


All Articles