将关联数组作为参数传递给jTemplates

Passing an associative array to jTemplates as a parameter

本文关键字:参数传递 jTemplates 关联 数组      更新时间:2023-09-26

我已经创建了一个jTemplate来显示一个"test"对象数组。该数组是一个常规索引数组。模板非常基础,只是使用一个{#foreach}来遍历数组中的项,并将它们显示在一个小表中。这个模板完成了这项工作,我得到了预期的输出。

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

然而,当我将数组传递给模板时,我得到一个关于脚本导致浏览器运行缓慢的错误,询问我是否想要停止它。它似乎处于某种无休止的循环中。我不确定模板是否正确读取数组。谁能告诉我如何使用jTemplates中的关联数组?

你的问题是你的数组认为它是巨大的:

_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