简体   繁体   English

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

[英]Passing an associative array to jTemplates as a parameter

I've created a jTemplate to display an array of "test" objects. 我创建了一个jTemplate来显示“测试”对象的数组。 The array is a regular indexed array. 该数组是一个常规索引数组。 The template is very basic, just uses a {#foreach} to iterate through the items in the array and displays them in a small table. 该模板非常基本,仅使用{#foreach}即可遍历数组中的项目并将其显示在一个小表中。 This template dos the job and I get the expected output. 这个模板完成了工作,我得到了预期的输出。

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

What I'd like to do is change my array to be an associative array and store my objects in it using the test's index. 我想做的是将数组更改为关联数组,并使用测试的索引将对象存储在其中。 This makes it easier to work with when I need to do some manipulation of the tests later on. 当以后需要对测试进行一些操作时,这使工作变得更容易。

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

However, when I pass the array to the template, I get an error about the script is causing my browswer to run slow, asking if I would like to stop it. 但是,当我将数组传递给模板时,出现有关该脚本的错误,导致浏览器运行缓慢,询问我是否要停止它。 It seems like its in some kind of endless loop. 似乎它处于无尽的循环中。 I'm not sure the template is reading the array correctly. 我不确定模板是否正确读取数组。 Can anyone tell me how I work with the associative array inside the jTemplates? 谁能告诉我我如何使用jTemplates中的关联数组?

You issue is that your array thinks it is huge: 您的问题是您的数组认为它是巨大的:

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

so you can do this: 因此您可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM