DIV CSS 佈局教程網

jQuery 範本資料綁定外掛的三大用法(含嵌套綁定)
編輯:JavaScript綜合知識     

用 JavaScript 手動拼接 HTML 字串來渲染列表,一旦欄位變多、結構變複雜,程式碼就會迅速失控。jQuery 的 tmpl 範本外掛把「資料」與「樣板」分開,是處理這類場景的乾淨解法。以下整理三種典型用法。

用法一:把後台資料綁到範本(無嵌套)

以通話記錄頁為例。先定義目標容器,內容是表頭:

<dl class="box_pannel_content_filled_border none" id="gvRecCalls">
  <dd class="bg_blue">
    <p class="width_level_half_2 fl nopitch"></p>
    <p class="width_level_half_5 bold fl">被叫號碼</p>
    <p class="width_level_half_5 bold fl">主叫號碼</p>
    <p class="width_level_half_6 bold fl">起始時間</p>
    <p class="width_level_half_4 bold fl" id="pAmount">金額($)</p>
    <p class="width_level_half_4 bold fl">時長</p>
    <p class="width_level_half_10 bold fl">區域</p>
    <p class="width_level_half_4 bold fl nopitch" name="pCDRHeader">CDR ID</p>
    <p class="width_level_half_2 fl none" name="pSelectCbHeader"></p>
    <p class="width_level_half_2 fr none" name="pDeleteCbHeader"></p>
  </dd>
</dl>

再定義資料範本,用 ${} 標記資料插入的位置。範本裡可以直接呼叫函式做格式化:

<dl id="RecCallsTemplate">
  <dd>
    <p class="center width_level_half_2 fl nopitch">
      <b class="${CallMode == 1 ? 'icon_call_in' : 'icon_call_out'}"></b>
    </p>
    <span class="width_level_half_5 fl"><span style="color:#FF0000;">${CalledStationId}</span></span>
    <span class="width_level_half_5 fl">${CallingStationId.substr(CallingStationId.indexOf("*") + 1)}</span>
    <span class="width_level_half_6 fl" id="Start_time">${StartTime}</span>
    <span class="width_level_half_4 fl">${CSSCommonJS.ChangeDecimal(Revenue,3)}</span>
    <span class="width_level_half_4 fl"><span style="color:#FF0000;">${CSSCommonJS.GetTimeFormatString(RevenueTime)}</span></span>
    <span class="width_level_half_10 fl">${Location}</span>
    <span class="width_level_half_4 fl nopitch" name="pCDRHeader">${CdrId}</span>
    <p class="right width_level_half_2 fr none" name="pSelectCbHeader">
      <input type="checkbox" name="cbSelect" class="label" /></p>
    <span class="fl none" name="pDeleteCbHeader">
      <button class="crm_btn norm" id="btDelete"><b>刪除</b></button>
    </span>
  </dd>
</dl>

綁定動作只需一行:

<script src="Scripts/jquery.tmpl.js" type="text/javascript"></script>
function RenderTemplatefunction(container, template, data) {
   $(template).tmpl(data).appendTo(container);  // 原始方法
};
CSSCommonJS.RenderTemplatefunction(
  $(t.panelID).find("#gvRecCalls"),
  $(t.panelID).find("#RecCallsTemplate"),
  result.CdrData);

${} 裡可以寫運算式,這讓三元判斷、substring、自訂格式化函式都能直接在範本中完成,省下大量後處理程式碼。

用法二:範本無佔位符,後台填充資料

有些情況資料結構不適合直接綁定,需要先把範本渲染出來,再逐一填入。許願牆就是這樣的例子。

前台先準備容器與隱藏的範本:

<div id="content">
  <!-- 模板數據 -->
  <div id="ItemList"></div>
  <!-- 模板數據 end -->
</div>

<div id="ItemTemplate" style="display: none;">
  <dd>
    <div class="items">
      <div class="bg">
        <div class="info">
          <a href="#" id="btnTitle"><span id="item_title"></span></a>
        </div>
        <div class="k"></div>
        <div class="person" id="item_person"></div>
        <div class="date" id="item_date"></div>
      </div>
    </div>
  </dd>
</div>

後台取資料、渲染、再逐一綁定內容與事件:

// 獲取許願牆數據
$.get("control/controler.ashx?t=" + new Date(),
    { type: 'heartwall', date: new Date() }, function (data) {
    var jsonData = eval("(" + data + ")");
    RenderTemplatefunction($("#ItemList"), $("#ItemTemplate"), jsonData.table);
    $("#ItemList").children("dd").each(function (index) {
      var tTr = this;
      var selectedItem = $.tmplItem(this);  // 取得該項的資料
      var tmp_title = $(tTr).find("#item_title");
      var tmp_person = $(tTr).find("#item_person");
      var tmp_date = $(tTr).find("#item_date");
      var btnTitle = $(tTr).find("#btnTitle");
      var bgNumber = "it" + Math.floor(Math.random() * 10 + 9) + ".jpg";
      $(tTr).find(".bg").css('background-image', "url('img/bg/" + bgNumber + "')");

      var getRandomColor = function () {
        return (function (m, s, c) {
          return (c ? arguments.callee(m, s, c - 1) : '#')
            + s[m.floor(m.random() * 16)]
        })(Math, '0123456789abcdef', 5)
      }
      $(tTr).find("#item_title").css('color', getRandomColor().toString());

      // 綁定資料
      tmp_title.html(selectedItem.data.title);
      tmp_person.html(selectedItem.data.pubName);
      tmp_date.html(selectedItem.data.addDate.toString().split(' ')[0].replaceAll('/', '-'));

      btnTitle.click(function () {
        var heart_date = "";
        if (selectedItem.data.beginDate.toString() == selectedItem.data.endDate.toString()) {
          heart_date = selectedItem.data.beginDate.toString().split(' ')[0].replaceAll('/', '-');
        } else {
          heart_date = selectedItem.data.beginDate.toString().split(' ')[0].replaceAll('/', '-')
            + " 至 " + selectedItem.data.endDate.toString().split(' ')[0].replaceAll('/', '-');
        }
        $("#heart_title").html(selectedItem.data.title);
        $("#heart_content").html(selectedItem.data.content);
        $("#heart_date").html(heart_date);
        $("#heart_person").html(selectedItem.data.participator);
        $("#heart_contact").html(selectedItem.data.contact);
        $("#heatr_puber").html(selectedItem.data.pubName);
        this.href = "#heartInfo_content";
        $(this).addClass("heartInfo_inline");
        $("#heartInfo_content").show();
        showDialog();
      });
    });
  });

這裡最值得記的是 $.tmplItem(this):它讓每個渲染出的節點都能取回自己對應的資料物件,避免了用 index 去反查陣列的麻煩。要留意的是 eval 解析 JSON 並不安全,正式環境應改用 JSON.parse 或 jQuery.parseJSON。

用法三:嵌套綁定

當資料源裡有多個陣列,需要各自綁到對應的子範本時,用 tmpl 標籤在範本內部再呼叫範本即可。以帳單頁為例:

目標容器與外層範本:

<span class="width_level_0 fl nopitch" id="ProductBilling"></span>

<div id="ProductBillingTemplate" class="none">
  <dl class="box_pannel_content_filled_special">
    <dd class="border_none_special_top">
      <p class="width_level_half_3 fl"></p>
      <span class="width_level_9 fl">
        <b class="bold" id="bComboName"></b> <b id="bTel"></b></span>
    </dd>
    {{tmpl(BillTransactions) "#BillingDetailDateTemplate"}}
    {{tmpl(RebateInstances) "#BillingDetailDateTemplate"}}
    {{tmpl(TopUpDetails) "#BillingDetailDateTemplate"}}
  </dl>
</div>

寫法固定:第一個參數是資料源中的陣列名稱,第二個是要使用的子範本。同一個子範本可以重複套用到不同陣列上。

子範本:

<div id="BillingDetailDateTemplate" class="none">
  <dd class="border_none_special">
    <p class="width_level_half_3 fl"></p>
    <p class="width_level_half_12 fl">
      ${(typeof(Name) == "undefined" ? Type : Name) + ":"}
    </p>
    <span class="width_level_1 fl" id="spamount" title="{{= CreateDate }}">
      ${CSSCommonJS.ChangeDecimal((typeof(InitialAmount) == "undefined" ? Amount : InitialAmount), 2)}
    </span>
    <span class="width_level_5 fl" id="spdescription">${Description}</span>
  </dd>
</div>

因為這個子範本是三個資料源的共同範本,屬性名稱可能不同,所以要用 typeof(X) == "undefined" 做條件判斷,在 Name/Type、InitialAmount/Amount 之間自動擇一。這是共用範本時很實用的小技巧。

後台綁定與後處理:

CSSCommonJS.RenderTemplatefunction(
  $(t.panelID).find("#ProductBilling"),
  $(t.panelID).find("#ProductBillingTemplate"),
  billingDetail);

$(t.panelID).find("#ProductBilling").children("dl").each(function (index) {
  var tTr = this;
  var selectedItem = $.tmplItem(this);
  var bComboName = $(tTr).find("#bComboName");
  var bTel = $(tTr).find("#bTel");
  var n = selectedItem.data;
  var curAcct = CSSCommonJS.GetCurrentUser(t.masterUser, n.AccountId);
  var curpstn = "";
  if (curAcct.AccountType == CSSAccountType.BB) {
    if (curAcct.DID) {
      if (curAcct.CountryCode == "1") {
        curpstn = "(Tel:" + CSSCommonJS.FormatUSCAPhone(curAcct.DID) + ")";
      } else {
        curpstn = "(Tel:" + curAcct.DID + ")";
      }
    } else if (curAcct.BBNumber) {
      curpstn = "(" + curAcct.BBNumber + ")";
    }
  } else if (curAcct.AccountType == CSSAccountType.HY) {
    curpstn = "(" + curAcct.HYNumber + ")";
  } else if (curAcct.AccountType == CSSAccountType.DSL) {
    curpstn = "(" + curAcct.DSLNumber + ")";
  }
  bComboName.html(curAcct.ComboName);
  bTel.html(curpstn);

  if ((n.BillTransactions.length + n.RebateInstances.length + n.TopUpDetails.length) == 0) {
    $(tTr).hide();  // 三個陣列都空就不顯示這一組
  }

  $(tTr).find(".border_none_special").each(function (spindex) {
    var tdd = this;
    var selectedItem = $.tmplItem(this);
    var spamount = $(tdd).find("#spamount");
    var spdescription = $(tdd).find("#spdescription");
    if (t.currentAdmin.Valid) {
      spamount.attr("title", spamount.attr("title").formatDate(t.masterUser, ""));
    } else {
      spdescription.hide();  // 權限不足時隱藏說明
    }
  });
});

嵌套的部分由範本引擎自動完成,我們只需在後處理階段用 each 逐層取得節點即可。這裡同時示範了兩種常見的後處理:資料為空時隱藏整組,以及依權限決定是否顯示描述欄位。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved