2011-09-20 109 views
0

我創建了一個jTemplate來顯示「測試」對象的數組。該數組是一個常規的索引數組。該模板非常基本,只需使用{#foreach}來遍歷數組中的項目並將它們顯示在一個小表中。這個模板做這項工作,我得到預期的輸出。將關聯數組傳遞給jTemplates作爲參數

// Setup the JTemplate. 
    $('#tests_div').setTemplate($('#tests_template').html()); 

    try { 

     // Process the JTemplate to display all currently selected tests. 
     $('#tests_div').processTemplate(_selectedTests); 
    } 
    catch (e) { 
     alert('Error with processing template: ' + e.Description); 
    } 


    <script type="text/html" id="tests_template"> 
     {#foreach $T as tests} 
      <table> 
      <tr> 
       <td>Index: {$T.tests.index}</td> 
       <td>Name: {$T.tests.firstname} {$T.tests.lastname}</td> 
       <td>Score: {$T.tests.score} </td> 
      </tr> 
      </table> 
     {#/for} 
    </script> 

我想什麼做的是改變我的數組是一個關聯數組,並使用測試的指標我的對象存儲在裏面。當我需要稍後對測試進行一些操作時,這使得它更容易處理。

var a = new Test; 
a.index = 12345678; 
_selectedTests[a.index] = a; 

然而,當我數組傳遞給模板,我得到的腳本錯誤導致我browswer運行緩慢,問我是否想停止它。它看起來像是在某種無盡的循環中。我不確定模板是否正確讀取數組。任何人都可以告訴我如何使用jTemplates中的關聯數組?

回答

1

您的問題是,您的數組認爲這是巨大的:

_selectedTests[12345678] = a; // creates an array of 12345678 elements!! length of 12345678 

,所以你可以這樣做:

_selectedTests[a.index.toString()] = a; // creates an associative array with one key "12345678", length of 1 
+0

這個工作,謝謝! – HashTagDevDude