【问题标题】:Changing a jQuery-template's HTML before appending to DOM在追加到 DOM 之前更改 jQuery 模板的 HTML
【发布时间】:2011-05-08 09:48:35
【问题描述】:

我在使用 jQuery 模板时遇到问题,就像使用普通 jQuery DOM 对象一样。在将模板函数创建的 HTML 附加到 DOM 之前,我需要更改它。
下面我的示例中的 cmets 解释了我想要做什么以及出了什么问题。

 <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>

【问题讨论】:

    标签: jquery jquery-templates


    【解决方案1】:

    您正在附加已删除的元素,如果要删除该元素,请附加剩余的内容,您需要使用.end() 跳回链中,如下所示:

    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();
    

    You can test it out here.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-03
      • 2017-02-09
      • 2011-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      相关资源
      最近更新 更多