[英]Passing an associative array to jTemplates as a parameter
我创建了一个jTemplate来显示“测试”对象的数组。 该数组是一个常规索引数组。 该模板非常基本,仅使用{#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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.