2011-05-24 232 views
0

我在綁定到JSON對象的<table>中插入行。表格中的單元格包含需要包含對象數量的<select>,因此7個對象將產生7 <option> s,1-7。如何使用jQuery.tmpl在<select>中渲染X <option>?

這可以在模板定義中完成嗎?

編輯:我添加了示例數據和標記。從這些數據中,我想將3 <option> s(1-3)添加到DisplayOrder <select>,併爲每個<select>選擇合適的<option>

例子:http://jsfiddle.net/4SxTS/

var data = [{ 
    "Id": 1, 
    "DisplayOrder": 1, 
    "LabelText": "Unit On-Line Status:"}, 
{ 
    "Id": 2, 
    "DisplayOrder": 2, 
    "LabelText": "AGC Pct:"}, 
{ 
    "Id": 3, 
    "DisplayOrder": 3, 
    "LabelText": "Main Steam Heat Rate 
}]; 

<table border="1" cellpadding="0" cellspacing="0"> 
    <thead><tr><th>Display Order</th><th>Label Text</th></tr></thead> 
    <tbody></tbody> 
</table> 

<script id="attributeTemplate" type="text/x-jquery-tmpl"> 
    <tr> 
     <td><select name="DisplayOrder"></select></td> 
     <td><input type="text" name="LabelText" value="${LabelText}" /></td> 
    </tr> 
</script> 
+0

你有可能給腳本應該產生一些示例html嗎? – stevevls 2011-05-24 21:02:56

+0

感謝您的更新。重新安排您的數據可能嗎? – 2011-05-25 16:13:51

回答

1

我不知道你的意思到底是什麼沒有一些樣本數據和標記,但我認爲你的問題的主要部分涉及循環數字和渲染option每個號碼的標籤。你可以通過創建一個包含「N」的元素,然後使用{{each}}數組做到這一點,但我認爲,使用自定義模板標籤的工作原理以及在這裏:

  1. 定義{{for}}標籤,通過數字迭代0到n:

    $.extend(jQuery.tmpl.tag, { 
        'for': { 
         open: "for(var $i = 0; $i < $1; $i++) {", 
         close: "}" 
        } 
    }); 
    
  2. 使用新的標籤的模板:

    <script type="text/html" id="row-tmpl"> 
        {{each Rows}} 
        <tr> 
         <td>${Title}</td> 
         <td>${Description}</td> 
         <td> 
          <select> 
           {{for $data.TotalObjects}} 
           <option>${$i}</option> 
           {{/for}} 
          </select> 
         </td> 
        </tr> 
        {{/each}} 
    </script> 
    

    一個名爲:

    var rows = { 
        TotalObjects: 5, 
        Rows: [{ 
         Title: 'Test Row', 
         Description: 'Test Row Description' 
        }, 
        { 
         Title: 'Another Row', 
         Description: 'Another Row Description' 
        }] 
    }; 
    

最佳表現在工作示例:http://jsfiddle.net/xgE3Y/

你的情況可能會更簡單,但我的答案應該讓你在每次迭代的模板和行爲至少使用一個簡單的for循環值。

0

也許是這樣的:

$(function() { 

     var thisSelectObjects = 8; 
     var thatSelectObjects = 2; 


     $.fn.setOptions = function (options) { 

      var settings = { 
       'selectNum': 1 
      }; 

      return this.each(function() { 
       if (options) { 
        $.extend(settings, options); 
       } 
       for (i = 0; i < settings.selectNum; i++) { 
        $(this).append('<option>' + i + '<option/>'); 
       } 
      }); 
     }; 



     $('#thisSelect').setOptions({ 'selectNum': thisSelectObjects }); 
     $('#thatSelect').setOptions({ 'selectNum': thatSelectObjects }); 

    }); 

HTML:

<body> 
    <select id='thisSelect'></select> 
    <select id='thatSelect'></select> 
</body> 
+0

我正在尋找使用jQuery.tmpl框架的東西。 – Homer 2011-05-25 17:10:09

+0

哎呀抱歉,我的工具字面上。就像製作一個模板化的代碼片段一樣 – XGreen 2011-05-25 17:34:34

相關問題