2011-09-20 106 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